diff --git a/docs/HLSD/python-plugin-wheel-installation.md b/docs/HLSD/python-plugin-wheel-installation.md new file mode 100644 index 0000000000..6076af5bb7 --- /dev/null +++ b/docs/HLSD/python-plugin-wheel-installation.md @@ -0,0 +1,57 @@ +# Python plugin wheel installation + +## Purpose and identity + +OrcaSlicer runs Python plugins in its embedded interpreter. A plugin's entry is a `.py` file or a wheel stored in its plugin directory. Discovery and metadata reading use that entry file; the wheel remains available after installation. Local plugin keys derive from the entry filename, while cloud plugins use their UUID. Those identities connect plugins to their settings, permissions, capabilities and other references and must not change because of how a wheel is installed. + +Writable plugin data is stored separately from the plugin package. Package removal or replacement must not inadvertently remove that data. + +## Installing wheels + +A wheel entry is installed with bundled `uv` and bundled Python when the plugin is loaded, unless a usable installation is already present. The target is the plugin's legacy extraction path, `/__whl_extracted__//`, which is also where the pre-uv loader extracted the entry wheel. That gives one cache location and one loading flow: the entry package is always imported from that directory, whether it was extracted before or installed by uv. The stored wheel, plugin key and `.install_state.json` sidecar remain where they are, preserving their settings, permissions and capability choices. A `.py` entry is still imported directly. + +`__whl_extracted__/` is shared with dependency wheels. A dependency wheel `.whl` is extracted to `__whl_extracted__//`, so only the entry package's own subdirectory is the installation target; dependency extractions alongside it are left alone. If a dependency wheel's filename stem equals the entry package, both would need the same directory and import name. Installation fails with a collision error instead of replacing the dependency extraction. + +An existing `__whl_extracted__//` without an installation marker is a pre-uv entry extraction. When it already contains the entry package it is used directly: the same directory import runs, and uv is not started, so its files are not rewritten. Only the entry package's own directory counts. The shared `__whl_extracted__/` parent, which holds dependency extractions, is never treated as an entry installation. A markerless target that does not contain the entry package is replaced. A target with a marker that is stale or invalid is a uv-managed installation and is also replaced, through the normal reinstall path. Plugin-owned data belongs in the separate plugin data directory. If uv fails before promotion, the previous directory is left untouched; if promotion fails, it is restored. Either way a markerless extraction remains usable until a replacement succeeds. + +The entry package is metadata-derived and becomes a path component and an import name. It must be a non-empty dotted name whose components are non-empty and contain no path separators, control characters, or characters Windows forbids in filenames. Non-ASCII Unicode names are allowed. This is path-component safety rather than full Python identifier validation: a name that cannot be imported fails when the module is imported. + +uv runs without contacting a package index and without installing dependencies: + +``` +uv --no-config pip install --python --no-python-downloads + --no-deps --no-index --no-cache --link-mode copy + --target +``` + +Declared dependencies continue to use the existing shared installation policy: they are installed separately by uv into the shared packages directory and added to the interpreter's import path. Wheel files next to the entry that are not the entry itself are extracted under `__whl_extracted__/` as before, alongside the entry target. + +The installed directory provides real filesystem paths for package resources. Wheel installation can relocate files compared with literal extraction, especially files in a wheel's `.data` directory. Plugins that derive resource paths from their package location should be checked against the installed layout. + +## Path spelling on Windows + +The plugin root, its `__whl_extracted__/` caches and the files below them can pass the legacy 260-character `MAX_PATH`. Filesystem probes and operations use the extended-length (`\\?\`) spelling where the plain spelling cannot reach a path; uv receives plain paths and qualifies them itself, and a `sys.path` entry keeps the plain spelling it was given whenever the import can be served through it. For an imported package or module that is decided from the entry files the finder probes: the plain spelling is kept while `/__init__.py`, a compiled `__init__` initializer, or the single-module `.py`/compiled extension also fit below the limit. A package with no `.py` entry, such as a namespace or compiled-only package, therefore keeps the plain spelling instead of being prefixed for lack of a file to probe, while any entry file past the limit selects the extended-length form. Dependency extraction roots follow the same rule, decided by whether the extraction root itself is reachable through the plain spelling. + +One limit remains: files nested below the entry are not probed individually. They are reached through the recorded `sys.path` entry, so a submodule that itself lies past the limit is only reached when the entry above it already selected the extended-length form. + +## Wheel filename reconstruction + +uv requires a valid PEP 427 wheel filename. A stored cloud download or a locally renamed wheel may not have one, so installation stages a copy under a name built from the wheel's own `METADATA` name and version and its declared `WHEEL` tags. The stored entry filename is not changed. The tag is selected from the tags the wheel declares; it is never invented, and uv performs the final interpreter/platform compatibility check. + +## Cache and reuse + +Installation happens in a staging directory, `__wheel_staging__-*`, and is promoted to `__whl_extracted__//` only after uv succeeds and the entry package is present. The previous target is moved to `__wheel_prev__-*` during promotion and restored if promotion fails; it is removed after a successful promotion. All of these names start with `__`, so discovery ignores them. + +A marker inside the installed target records the installation format, interpreter ABI, entry package, wheel size and a fingerprint of the wheel bytes. A later load reuses the target when all of them match, so unchanged wheels do not run uv again. A markerless target that contains the entry package is a pre-uv extraction and is reused directly. Any marker that does not match the current wheel, format or ABI causes reinstallation, so a stale uv installation is never reused. The marker is a cache hint, not evidence that a plugin is trustworthy. The entry package must still be identified independently of the distribution name. + +Legacy acceptance and uv installation take the same lock, so a load never accepts a markerless target while another load is rebuilding it. + +The local plugin cache-clear action removes `__whl_extracted__/`, including the entry installation and all dependency extractions. It does not remove the stored wheel, the sidecar or the separate plugin data directory. + +## Failure and lifecycle + +If uv fails or the promoted target is incomplete, the load fails with an error naming the installation problem. There is no silent fallback to extraction. The previous target is restored if promotion fails, and the stored wheel, sidecar, settings and permissions are left in place, so a later load can retry once the problem is resolved. + +Native extensions may remain loaded after a plugin is stopped, particularly on Windows, so replacing or removing their files may require an application restart. + +Each plugin's installation directory is private, but plugins share one interpreter, `sys.path`, `sys.modules` and the dependency directory. Separate directories do not isolate conflicting imports. Installation and execution of plugin code are not security sandboxes. diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 5c4d1e951b..a1ef07005a 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -1735,29 +1735,28 @@ void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clea [plugin_key, was_loaded, clear_cache]() -> std::pair { PluginManager& manager = PluginManager::instance(); - boost::filesystem::path cache_dir; + boost::filesystem::path plugin_root; if (clear_cache) { PluginDescriptor descriptor; if (!manager.try_get_plugin_descriptor(plugin_key, descriptor)) return {false, _u8L("Plugin not found.")}; - boost::filesystem::path resolved_root; - std::string resolve_error; + std::string resolve_error; if (!resolve_allowed_plugin_root(descriptor, {get_orca_plugins_dir()}, _u8L("Refusing to clear a plugin cache outside the local plugin directory."), - resolved_root, resolve_error)) + plugin_root, resolve_error)) return {false, resolve_error}; - cache_dir = resolved_root / "__whl_extracted__"; } if (!manager.unload_plugin(plugin_key)) return {false, _u8L("Failed to unload plugin.")}; if (clear_cache) { - boost::system::error_code ec; - boost::filesystem::remove_all(cache_dir, ec); - if (ec) - return {false, GUI::format(_u8L("Failed to clear plugin cache: %1%"), ec.message())}; + // __whl_extracted__ holds both dependency extractions and the uv-installed + // entry wheel. The stored wheel and plugin data are left untouched. + std::string cache_error; + if (!plugin_wheel_install::delete_install_cache(plugin_root, cache_error)) + return {false, cache_error}; } manager.load_plugin(plugin_key, false); diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index cf247043cc..233fcb1b3d 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -641,13 +641,56 @@ bool same_path_component(const boost::filesystem::path& lhs, const boost::filesy #endif } +#ifdef _WIN32 +// Windows spells some locations two ways: the plain form ("C:\dir", "\\server\share\dir") and the +// documented extended-length form ("\\?\C:\dir", "\\?\UNC\server\share\dir"). A plugin's __file__ +// carries whichever spelling its sys.path entry used, and a path canonicalized past MAX_PATH is +// necessarily extended, while allowed roots and grants are registered in the plain form. The +// prefix adds a root-name component ("\\?\C:" sees "C:", "\\?\UNC" sees "\\server"), so a +// component-wise comparison would never match. Rewrite the two documented aliases to the plain +// spelling here; the result is only compared, never used for I/O. Every other device-namespace +// path ("\\?\Volume{...}", "\\?\PIPE\...", "\\.\pipe\...", "\\.\PhysicalDrive0", "\??\C:\...") +// names something this normalization cannot reinterpret, so it is left exactly as written and +// keeps failing closed against a plain root. +boost::filesystem::path plain_spelling(const boost::filesystem::path& path) +{ + const std::wstring native = path.native(); + + // "\\?\UNC\server\share\..." -> "\\server\share\..." (the Win32 UNC alias). + constexpr std::size_t unc_prefix_length = 8; // "\\?\UNC\" + if (native.rfind(L"\\\\?\\UNC\\", 0) == 0) + return boost::filesystem::path(L"\\\\" + native.substr(unc_prefix_length)); + + // "\\?\C:\..." -> "C:\..." for a drive-letter root only. "\\?\UNC\..." is handled above, and + // anything else after the prefix is a different namespace, not a longer name for a drive path. + constexpr std::size_t prefix_length = 4; // "\\?\" + if (native.rfind(L"\\\\?\\", 0) == 0 && native.size() > prefix_length + 1) { + const wchar_t drive = native[prefix_length]; + const bool letter = (drive >= L'A' && drive <= L'Z') || (drive >= L'a' && drive <= L'z'); + if (letter && native[prefix_length + 1] == L':') + return boost::filesystem::path(native.substr(prefix_length)); + } + + return path; +} +#else +boost::filesystem::path plain_spelling(const boost::filesystem::path& path) +{ + return path; +} +#endif + // True when two canonical paths name the same location: every component must match, using the // platform's case rule. Unlike suffix_inside_root() this is full equality, so a lookalike that // merely shares a prefix -- or a file beside the granted one -- can never match. bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesystem::path& rhs) { - auto lhs_it = lhs.begin(), lhs_end = lhs.end(); - auto rhs_it = rhs.begin(), rhs_end = rhs.end(); + // Compare in the plain spelling; see plain_spelling(). + const boost::filesystem::path plain_lhs = plain_spelling(lhs); + const boost::filesystem::path plain_rhs = plain_spelling(rhs); + + auto lhs_it = plain_lhs.begin(), lhs_end = plain_lhs.end(); + auto rhs_it = plain_rhs.begin(), rhs_end = plain_rhs.end(); for (; lhs_it != lhs_end && rhs_it != rhs_end; ++lhs_it, ++rhs_it) { if (!same_path_component(*lhs_it, *rhs_it)) return false; @@ -658,18 +701,24 @@ bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesy // Component-wise containment: the whole of canonical_root must be a prefix of // canonical_candidate, and the remaining components must not traverse upward. Both arguments are // expected to come from canonicalize_for_comparison()/canonical_folder(), i.e. expanded to long -// names where the platform has 8.3 aliases. On a match, suffix receives the candidate's -// components below the root (empty when the two paths are equal). +// names where the platform has 8.3 aliases and possibly carrying the extended-length prefix. On a +// match, suffix receives the candidate's components below the root (empty when the two paths are +// equal). bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, const boost::filesystem::path& canonical_root, boost::filesystem::path& suffix) { suffix.clear(); - auto cand_it = canonical_candidate.begin(); - auto cand_end = canonical_candidate.end(); - auto root_it = canonical_root.begin(); - auto root_end = canonical_root.end(); + // Compare in the plain spelling; see plain_spelling(). The components below the root never + // carry the prefix, so the suffix is unaffected. + const boost::filesystem::path candidate = plain_spelling(canonical_candidate); + const boost::filesystem::path root = plain_spelling(canonical_root); + + auto cand_it = candidate.begin(); + auto cand_end = candidate.end(); + auto root_it = root.begin(); + auto root_end = root.end(); // Consume matching components while (root_it != root_end && cand_it != cand_end && same_path_component(*root_it, *cand_it)) { @@ -697,9 +746,9 @@ bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root) { // Both sides are canonicalized identically, including the expansion of Windows 8.3 short - // names, so a root registered under one spelling still contains a target reported under the - // other. A side that cannot be normalized fails closed: comparing differently spelled paths - // could otherwise report containment that does not hold. + // names and the extended-length prefix, so a root registered under one spelling still contains + // a target reported under the other. A side that cannot be normalized fails closed: comparing + // differently spelled paths could otherwise report containment that does not hold. boost::filesystem::path canonical_candidate; if (!canonicalize_for_comparison(candidate, canonical_candidate)) return false; diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index 480fc3f2e7..a1215949a3 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -9,12 +9,13 @@ #include #include #include +#include #include #include #include +#include #include #include -#include #ifdef _WIN32 #ifndef NOMINMAX @@ -43,8 +44,11 @@ #include #include #include +#include #include +#include #include +#include #include #include #include @@ -53,6 +57,29 @@ namespace Slic3r { const char* const INSTALL_STATE_FILE = ".install_state.json"; +namespace { + +// Narrow path for boost::nowide streams and C stdio. On Windows the extended-length ("\\?\") form +// reaches past MAX_PATH even with LongPathsEnabled off; elsewhere the path is unchanged. Keep this +// out of boost::filesystem::path::generic_string(), which rewrites the separators the prefix needs. +std::string io_path_string(const boost::filesystem::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(extended_path(path).wstring()); +#else + return path.string(); +#endif +} + +} // namespace + +bool has_wheel_extension(const boost::filesystem::path& path) +{ + std::string ext = path.extension().string(); + boost::algorithm::to_lower(ext); + return ext == ".whl"; +} + std::mutex& install_state_mutex() { // Function-local static: safe to use from any writer regardless of static initialization order. @@ -199,7 +226,7 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: for (;;) { ++attempts; ec.clear(); - removed_count = fs::remove_all(resolved_root, ec); + removed_count = fs::remove_all(extended_path(resolved_root), ec); if (!ec) break; @@ -226,6 +253,12 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: return false; } + if (removed_count == 0) { + BOOST_LOG_TRIVIAL(warning) << "Plugin deletion removed 0 files from " << resolved_root.string() + << "; the folder may already be absent or may not have been accessible."; + return true; + } + if (attempts > 1) { // Recovered after one or more transient failures: keep the last failure for diagnosis. BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string() @@ -235,16 +268,12 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: return true; } - if (removed_count == 0) { - return true; - } - BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string(); return true; #else // Non-Windows behavior is unchanged: one remove_all() call, no retries. boost::system::error_code ec; - const auto removed_count = fs::remove_all(resolved_root, ec); + const auto removed_count = fs::remove_all(extended_path(resolved_root), ec); if (ec) { // TRN %1% is a folder path, %2% the system error message. error = GUI::format(_u8L("Failed to delete plugin folder %1%: %2%"), resolved_root.string(), ec.message()); @@ -252,6 +281,8 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: } if (removed_count == 0) { + BOOST_LOG_TRIVIAL(warning) << "Plugin deletion removed 0 files from " << resolved_root.string() + << "; the folder may already be absent or may not have been accessible."; return true; } @@ -280,17 +311,21 @@ void scan_plugin_directory(const std::string& dir_path, std::vectorstatus())) continue; - const fs::path plugin_dir = it->path(); + const fs::path plugin_dir = fs::path(dir_path) / it->path().filename(); if (is_ignored_plugin_directory(plugin_dir)) continue; @@ -315,7 +350,7 @@ void scan_plugin_directory(const std::string& dir_path, std::vector get_plugin_directories(const std::string& cloud_user_id // Creates the directory when missing — callers (notably the install path) rely on it existing. auto add_or_create_dir = [&dirs](const fs::path& path) { - if (fs::exists(path) && fs::is_directory(path)) { + const fs::path io_path = extended_path(path); + if (fs::exists(io_path) && fs::is_directory(io_path)) { dirs.push_back(path.string()); return; } try { - fs::create_directories(path); + fs::create_directories(io_path); dirs.push_back(path.string()); BOOST_LOG_TRIVIAL(info) << "Created plugin directory: " << path.string(); } catch (const std::exception& ex) { @@ -461,6 +497,84 @@ std::string normalize_zip_entry_name(std::string entry_name) return entry_name; } +// Locate the single ".dist-info/" directory in a wheel. Returns false when there is none or +// when the archive holds more than one. +bool find_wheel_dist_info_dir(mz_zip_archive& archive, std::string& dist_info_dir, std::string& error) +{ + dist_info_dir.clear(); + + // Scan ALL entries, not just directory entries — some zip writers omit + // explicit directory entries. normalize_zip_entry_name strips trailing + // slashes, so we match ".dist-info" as the last path component of a + // directory entry, and ".dist-info/" embedded in a file path. + const mz_uint num_entries = mz_zip_reader_get_num_files(&archive); + mz_zip_archive_file_stat stat; + + for (mz_uint i = 0; i < num_entries; ++i) { + if (!mz_zip_reader_file_stat(&archive, i, &stat)) + continue; + + std::string entry_name = normalize_zip_entry_name(zip_entry_name(archive, stat)); + if (entry_name.empty()) + continue; + + // Find .dist-info as a path component. + size_t pos = entry_name.find(".dist-info"); + if (pos == std::string::npos) + continue; + + std::string candidate; + if (pos + 10 == entry_name.size()) { + // Directory entry itself (trailing / stripped by normalize). + candidate = entry_name + "/"; + } else if (pos + 10 < entry_name.size() && entry_name[pos + 10] == '/') { + // File inside .dist-info/: name.dist-info/METADATA + candidate = entry_name.substr(0, pos + 11); // include trailing / + } else { + continue; // .dist-info mid-name, not a path component. + } + + if (!dist_info_dir.empty() && candidate != dist_info_dir) { + error = "Wheel contains multiple .dist-info directories: " + dist_info_dir + " and " + candidate; + return false; + } + dist_info_dir = candidate; + } + + if (dist_info_dir.empty()) { + error = "Wheel does not contain a .dist-info directory"; + return false; + } + + return true; +} + +// All Tag: values declared by a WHEEL file, in file order. +std::vector parse_wheel_tags(const std::string& wheel_content) +{ + std::vector tags; + + std::istringstream stream(wheel_content); + std::string line; + while (std::getline(stream, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) + line.pop_back(); + if (line.rfind("Tag:", 0) != 0) + continue; + + std::string tag = line.substr(4); + size_t start = 0; + size_t end = tag.size(); + while (start < end && (tag[start] == ' ' || tag[start] == '\t')) + ++start; + while (end > start && (tag[end - 1] == ' ' || tag[end - 1] == '\t')) + --end; + tags.push_back(tag.substr(start, end - start)); + } + + return tags; +} + struct ZipReaderGuard { mz_zip_archive archive; @@ -913,8 +1027,9 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& // unreadable parent be told apart from a genuinely missing sidecar. Only "no entry" means a // new plugin whose metadata may be seeded; anything else that cannot be read must be // preserved. + const fs::path io_sidecar_path = extended_path(sidecar_path); boost::system::error_code ec; - const fs::file_status link_status = fs::symlink_status(sidecar_path, ec); + const fs::file_status link_status = fs::symlink_status(io_sidecar_path, ec); if (ec) { if (ec == boost::system::errc::no_such_file_or_directory) return InstallStateReadStatus::Absent; @@ -923,11 +1038,11 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& if (!fs::exists(link_status)) return InstallStateReadStatus::Absent; - const fs::file_status status = fs::status(sidecar_path, ec); + const fs::file_status status = fs::status(io_sidecar_path, ec); if (ec || !fs::is_regular_file(status)) return InstallStateReadStatus::Unreadable; - boost::nowide::ifstream f(sidecar_path.string()); + boost::nowide::ifstream f(io_path_string(io_sidecar_path)); if (!f) return InstallStateReadStatus::Unreadable; @@ -938,7 +1053,13 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& // would look malformed too. They count as malformed only when the entry itself is a // regular file, not a link that a move could follow on Windows, and a second read gets // every byte on disk (load_string_file throws otherwise, caught below) that still - // does not parse. + // does not parse. That second read stays on load_string_file() because only it proves a + // full read: copying the streambuf into a stream reports a short or failed read as + // end-of-stream, and a truncated prefix that fails to parse would be misclassified as + // malformed and set aside. It is called with the plain path: load_string_file() goes + // through path::generic_string(), whose forward slashes the "\\?\" prefix does not + // accept, so a sidecar past MAX_PATH fails that read and stays Unreadable, never + // malformed. if (malformed != nullptr && fs::is_regular_file(link_status)) { std::string contents; load_string_file(sidecar_path, contents); @@ -1050,14 +1171,19 @@ bool replace_install_state_file(const boost::filesystem::path& target, const std (target.filename().string() + "." + std::to_string(get_current_pid()) + "." + std::to_string(counter.fetch_add(1, std::memory_order_relaxed)) + ".tmp"); - const auto fail = [&tmp_path, &error](const std::string& reason) { + // Every file operation below uses the extended-length form, so a sidecar past MAX_PATH is still + // replaced atomically; the plain paths stay for the error messages. + const fs::path io_tmp_path = extended_path(tmp_path); + const fs::path io_target_path = extended_path(target); + + const auto fail = [&io_tmp_path, &error](const std::string& reason) { boost::system::error_code remove_ec; - fs::remove(tmp_path, remove_ec); + fs::remove(io_tmp_path, remove_ec); error = reason; return false; }; - boost::nowide::ofstream out(tmp_path.string(), std::ios::out | std::ios::trunc); + boost::nowide::ofstream out(io_path_string(io_tmp_path), std::ios::out | std::ios::trunc); if (!out) return fail("cannot open temporary for writing"); @@ -1076,14 +1202,14 @@ bool replace_install_state_file(const boost::filesystem::path& target, const std // Keep the replaced file's mode where the platform has one. Best effort, matching the previous // writer; a failure here does not turn a successful replace into a failed one. boost::system::error_code perm_ec; - const fs::file_status target_status = fs::status(target, perm_ec); + const fs::file_status target_status = fs::status(io_target_path, perm_ec); if (!perm_ec && fs::exists(target_status)) - fs::permissions(tmp_path, target_status.permissions(), perm_ec); + fs::permissions(io_tmp_path, target_status.permissions(), perm_ec); #endif #ifdef _WIN32 - const std::wstring wide_tmp = tmp_path.wstring(); - const std::wstring wide_target = target.wstring(); + const std::wstring wide_tmp = io_tmp_path.wstring(); + const std::wstring wide_target = io_target_path.wstring(); // A scanner or a reader holding the target open makes MoveFileExW fail transiently with a // sharing or access error. Retry the same replace primitive a bounded number of times; any // other error, or the last attempt, reports the last error and removes the temporary. @@ -1100,7 +1226,7 @@ bool replace_install_state_file(const boost::filesystem::path& target, const std ::Sleep(10); } #else - if (boost::nowide::rename(tmp_path.string().c_str(), target.string().c_str()) != 0) + if (boost::nowide::rename(io_tmp_path.string().c_str(), io_target_path.string().c_str()) != 0) return fail(std::error_code(errno, std::generic_category()).message()); #endif @@ -1200,12 +1326,13 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD { namespace fs = boost::filesystem; - if (!fs::exists(py_path) || !fs::is_regular_file(py_path)) { + const fs::path io_py_path = extended_path(py_path); + if (!fs::exists(io_py_path) || !fs::is_regular_file(io_py_path)) { error = "Python plugin file does not exist: " + py_path.string(); return false; } - boost::nowide::ifstream f(py_path.string()); + boost::nowide::ifstream f(io_path_string(py_path)); if (!f) { error = "Failed to open Python plugin file: " + py_path.string(); return false; @@ -1281,116 +1408,84 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD return true; } -bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error) +namespace { + +// The archive, METADATA and WHEEL contents shared by the two wheel metadata readers. The reader is +// kept open so a caller can read further .dist-info files (RECORD, top_level.txt). +struct WheelPrologue +{ + ZipReaderGuard reader; + std::string dist_info_dir; + std::string wheel; + std::string name; + std::string version; + std::string summary; + std::string author; + std::string import_name; + std::vector requires_dist; +}; + +// Open the wheel, locate its single .dist-info directory, and read METADATA and WHEEL. +bool read_wheel_prologue(const boost::filesystem::path& whl_path, WheelPrologue& out, std::string& error) { namespace fs = boost::filesystem; - if (!fs::exists(whl_path) || !fs::is_regular_file(whl_path)) { + const fs::path io_whl_path = extended_path(whl_path); + if (!fs::exists(io_whl_path) || !fs::is_regular_file(io_whl_path)) { error = "Wheel plugin file does not exist: " + whl_path.string(); return false; } - ZipReaderGuard reader; - if (!open_zip_reader(&reader.archive, whl_path.string())) { - error = "Failed to open wheel as zip: " + MZ_Archive::get_errorstr(mz_zip_get_last_error(&reader.archive)); + if (!open_zip_reader(&out.reader.archive, whl_path.string())) { + error = "Failed to open wheel as zip: " + MZ_Archive::get_errorstr(mz_zip_get_last_error(&out.reader.archive)); return false; } - reader.opened = true; + out.reader.opened = true; - // Find the single .dist-info directory. - // Scan ALL entries, not just directory entries — some zip writers omit - // explicit directory entries. normalize_zip_entry_name strips trailing - // slashes, so we match ".dist-info" as the last path component of a - // directory entry, and ".dist-info/" embedded in a file path. - const mz_uint num_entries = mz_zip_reader_get_num_files(&reader.archive); - std::string dist_info_dir; - mz_zip_archive_file_stat stat; - - for (mz_uint i = 0; i < num_entries; ++i) { - if (!mz_zip_reader_file_stat(&reader.archive, i, &stat)) - continue; - - std::string entry_name = normalize_zip_entry_name(zip_entry_name(reader.archive, stat)); - if (entry_name.empty()) - continue; - - // Find .dist-info as a path component. - size_t pos = entry_name.find(".dist-info"); - if (pos == std::string::npos) - continue; - - std::string candidate; - if (pos + 10 == entry_name.size()) { - // Directory entry itself (trailing / stripped by normalize). - candidate = entry_name + "/"; - } else if (pos + 10 < entry_name.size() && entry_name[pos + 10] == '/') { - // File inside .dist-info/: name.dist-info/METADATA - candidate = entry_name.substr(0, pos + 11); // include trailing / - } else { - continue; // .dist-info mid-name, not a path component. - } - - if (!dist_info_dir.empty() && candidate != dist_info_dir) { - error = "Wheel contains multiple .dist-info directories: " + dist_info_dir + " and " + candidate; - return false; - } - dist_info_dir = candidate; - } - - if (dist_info_dir.empty()) { - error = "Wheel does not contain a .dist-info directory"; - return false; - } - - // Read METADATA. - const std::string metadata_path = dist_info_dir + "METADATA"; - std::string meta_content; - if (!read_zip_text_file(reader.archive, metadata_path.c_str(), meta_content, error)) + if (!find_wheel_dist_info_dir(out.reader.archive, out.dist_info_dir, error)) return false; - std::string meta_name, meta_version, meta_summary, meta_author, meta_requires_python, meta_import_name; - std::vector requires_dist; + std::string metadata_content; + if (!read_zip_text_file(out.reader.archive, (out.dist_info_dir + "METADATA").c_str(), metadata_content, error)) + return false; + + std::string requires_python; std::string meta_error; - parse_metadata_rfc822(meta_content, meta_name, meta_version, meta_summary, meta_author, - meta_requires_python, meta_import_name, requires_dist, meta_error); + parse_metadata_rfc822(metadata_content, out.name, out.version, out.summary, out.author, requires_python, + out.import_name, out.requires_dist, meta_error); - if (meta_name.empty()) { + if (out.name.empty()) { error = "Wheel METADATA missing required Name field"; return false; } - if (meta_version.empty()) { + if (out.version.empty()) { error = "Wheel METADATA missing required Version field"; return false; } - // Read WHEEL (verify existence and Wheel-Version). - const std::string wheel_path = dist_info_dir + "WHEEL"; - std::string wheel_content; - if (!read_zip_text_file(reader.archive, wheel_path.c_str(), wheel_content, error)) + if (!read_zip_text_file(out.reader.archive, (out.dist_info_dir + "WHEEL").c_str(), out.wheel, error)) return false; + + return true; +} + +} // namespace + +bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error) +{ + WheelPrologue wheel; + if (!read_wheel_prologue(whl_path, wheel, error)) + return false; + // Verify there's at least a Wheel-Version header line. - if (wheel_content.find("Wheel-Version:") == std::string::npos) { + if (wheel.wheel.find("Wheel-Version:") == std::string::npos) { error = "Wheel WHEEL file missing Wheel-Version header"; return false; } // Parse and validate wheel platform tags. { - std::vector wheel_tags; - std::istringstream wstream(wheel_content); - std::string wline; - while (std::getline(wstream, wline)) { - while (!wline.empty() && (wline.back() == '\r' || wline.back() == '\n')) - wline.pop_back(); - if (wline.rfind("Tag:", 0) == 0) { - std::string tag = wline.substr(4); - size_t s = 0, e = tag.size(); - while (s < e && (tag[s] == ' ' || tag[s] == '\t')) ++s; - while (e > s && (tag[e - 1] == ' ' || tag[e - 1] == '\t')) --e; - wheel_tags.push_back(tag.substr(s, e - s)); - } - } - + const std::vector wheel_tags = parse_wheel_tags(wheel.wheel); if (!wheel_tags.empty()) { bool compatible = false; const std::string abi_tag = PythonInterpreter::python_abi_tag(); @@ -1428,9 +1523,9 @@ bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginD } // Read RECORD (verify existence). - const std::string record_path = dist_info_dir + "RECORD"; + const std::string record_path = wheel.dist_info_dir + "RECORD"; std::string record_content; - if (!read_zip_text_file(reader.archive, record_path.c_str(), record_content, error)) + if (!read_zip_text_file(wheel.reader.archive, record_path.c_str(), record_content, error)) return false; if (record_content.empty()) { error = "Wheel RECORD file is empty"; @@ -1439,9 +1534,9 @@ bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginD // Parse top_level.txt if present. std::string top_level; - const std::string top_level_path = dist_info_dir + "top_level.txt"; + const std::string top_level_path = wheel.dist_info_dir + "top_level.txt"; std::string top_level_content; - if (read_zip_text_file(reader.archive, top_level_path.c_str(), top_level_content, error)) { + if (read_zip_text_file(wheel.reader.archive, top_level_path.c_str(), top_level_content, error)) { // top_level.txt contains one package name per line. std::istringstream tl_stream(top_level_content); std::string tl_line; @@ -1466,31 +1561,51 @@ bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginD // 2. Core Metadata Import-Name. // 3. top_level.txt if unambiguous. // 4. Normalized Name as fallback. - if (!meta_import_name.empty()) { - descriptor.entry_package = meta_import_name; + if (!wheel.import_name.empty()) { + descriptor.entry_package = wheel.import_name; } else if (!top_level.empty()) { descriptor.entry_package = top_level; } else { - descriptor.entry_package = normalize_package_name(meta_name); + descriptor.entry_package = normalize_package_name(wheel.name); } - descriptor.dependencies = std::move(requires_dist); + descriptor.dependencies = std::move(wheel.requires_dist); // Populate local identity fallbacks from wheel metadata. // Cloud metadata will override these when available. - descriptor.name = sanitize_plugin_name(meta_name); - descriptor.version = meta_version; - descriptor.description = meta_summary; - descriptor.author = meta_author; + descriptor.name = sanitize_plugin_name(wheel.name); + descriptor.version = wheel.version; + descriptor.description = wheel.summary; + descriptor.author = wheel.author; return true; } +bool read_wheel_install_metadata(const boost::filesystem::path& whl_path, WheelInstallMetadata& out, std::string& error) +{ + out = {}; + error.clear(); + + WheelPrologue wheel; + if (!read_wheel_prologue(whl_path, wheel, error)) + return false; + + out.name = std::move(wheel.name); + out.version = std::move(wheel.version); + out.tags = parse_wheel_tags(wheel.wheel); + return true; +} + boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::path& plugin_dir, std::string& error) { namespace fs = boost::filesystem; - if (!fs::exists(plugin_dir) || !fs::is_directory(plugin_dir)) { + // The entry file is a direct child, so it can pass MAX_PATH while the plugin folder itself still + // resolves. Probe the folder and its children in extended form, then return children joined to + // the caller's `plugin_dir`: that path is stored in the descriptor, passed to uv, and shown in + // the UI, and must keep its normal spelling. + const fs::path io_plugin_dir = extended_path(plugin_dir); + if (!fs::exists(io_plugin_dir) || !fs::is_directory(io_plugin_dir)) { error = GUI::format(_u8L("Plugin directory does not exist: %1%"), plugin_dir.string()); return {}; } @@ -1498,29 +1613,30 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat fs::path py_entry; fs::path whl_entry; - for (fs::directory_iterator it(plugin_dir); it != fs::directory_iterator(); ++it) { - if (is_ignored_plugin_directory(it->path())) + for (fs::directory_iterator it(io_plugin_dir); it != fs::directory_iterator(); ++it) { + const fs::path entry = plugin_dir / it->path().filename(); + if (is_ignored_plugin_directory(entry)) continue; if (!fs::is_regular_file(it->status())) continue; - const fs::path ext = it->path().extension(); + const fs::path ext = entry.extension(); if (ext == ".py") { if (!py_entry.empty()) { // TRN %1% and %2% are file names. error = GUI::format(_u8L("Plugin directory contains multiple .py files: %1% and %2%"), - py_entry.filename().string(), it->path().filename().string()); + py_entry.filename().string(), entry.filename().string()); return {}; } - py_entry = it->path(); - } else if (ext == ".whl") { + py_entry = entry; + } else if (has_wheel_extension(entry)) { if (!whl_entry.empty()) { // TRN %1% and %2% are file names. error = GUI::format(_u8L("Plugin directory contains multiple .whl files: %1% and %2%"), - whl_entry.filename().string(), it->path().filename().string()); + whl_entry.filename().string(), entry.filename().string()); return {}; } - whl_entry = it->path(); + whl_entry = entry; } } @@ -1612,3 +1728,913 @@ std::vector collect_resource_texture_files(const std::string& dir, } } // namespace Slic3r + +// ── uv wheel installation ───────────────────────────────────────────── + +namespace Slic3r::plugin_wheel_install { +namespace { + +namespace fs = boost::filesystem; + +bool is_tag_char(char ch) +{ + const unsigned char uch = static_cast(ch); + return std::isalnum(uch) || ch == '.' || ch == '_' || ch == '+'; +} + +// PEP 427: runs of characters outside the allowed set become a single '_' in the escaped +// component. Both keep [A-Za-z0-9.] plus `extra_chars`: a name '_', a version the characters a +// PEP 440 version may contain, including the '!' epoch separator. +std::string escape_wheel_component(const std::string& value, const std::string& extra_chars) +{ + std::string escaped; + escaped.reserve(value.size()); + bool pending_separator = false; + for (unsigned char ch : value) { + const char c = static_cast(ch); + if (std::isalnum(ch) || ch == '.' || extra_chars.find(c) != std::string::npos) { + if (pending_separator && !escaped.empty()) + escaped += '_'; + pending_separator = false; + escaped += c; + } else { + pending_separator = true; + } + } + return escaped; +} + +std::vector split_tag(const std::string& tag) +{ + std::vector parts; + std::string part; + for (char ch : tag) { + if (ch == '-') { + parts.push_back(part); + part.clear(); + } else { + part += ch; + } + } + parts.push_back(part); + return parts; +} + +bool starts_with_digits_after(const std::string& value, const char* prefix) +{ + const std::string prefix_string(prefix); + if (value.compare(0, prefix_string.size(), prefix_string) != 0) + return false; + return value.size() > prefix_string.size() && std::isdigit(static_cast(value[prefix_string.size()])) != 0; +} + +bool looks_like_python_tag(const std::string& tag) +{ + return starts_with_digits_after(tag, "py") || starts_with_digits_after(tag, "cp") || starts_with_digits_after(tag, "pp") || + tag.compare(0, 7, "graalpy") == 0; +} + +bool looks_like_abi_tag(const std::string& tag) +{ + return tag == "none" || tag == "abi3" || starts_with_digits_after(tag, "cp") || starts_with_digits_after(tag, "pp") || + tag.compare(0, 6, "pypy") == 0; +} + +bool looks_like_platform_tag(const std::string& tag) +{ + if (tag == "any") + return true; + + static constexpr const char* const tokens[] = {"manylinux", "musllinux", "linux", "win", "macosx", "freebsd", + "android", "ios", "openbsd", "netbsd", "solaris", "aix"}; + for (const char* token : tokens) { + if (tag.find(token) != std::string::npos) + return true; + } + return false; +} + +// True when the three tag components name a real Python/ABI/platform combination shape, not just +// three dash-separated words. This is what separates a wheel filename from a generated download +// name (cloud_plugin-.whl also splits into five components). +bool looks_like_wheel_tags(const std::string& python_tag, const std::string& abi, const std::string& platform) +{ + return looks_like_python_tag(python_tag) && looks_like_abi_tag(abi) && looks_like_platform_tag(platform); +} + +bool names_equal_case_insensitive(const std::string& lhs, const std::string& rhs) +{ + return lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](unsigned char a, unsigned char b) { + return std::tolower(a) == std::tolower(b); + }); +} + +// Path-component safety for a metadata-derived package name. Bytes >= 0x80 are left alone so +// non-ASCII (Unicode) import names are not rejected. ASCII path separators, control characters and +// characters Windows forbids in filenames are refused. This is deliberately not a Python +// identifier check: the import step reports a name that cannot be imported. +bool is_safe_package_path_char(unsigned char ch) +{ + if (ch >= 0x80) + return true; + if (ch < 0x20 || ch == 0x7F) + return false; + + switch (ch) { + case '/': + case '\\': + case ':': + case '<': + case '>': + case '"': + case '|': + case '?': + case '*': + return false; + default: + return true; + } +} + +// A dependency wheel .whl is extracted to __whl_extracted__//. If that stem equals the +// entry package, the entry target and the dependency extraction are the same directory. Compare +// case-insensitively so a case-insensitive filesystem cannot hide the collision. +bool dependency_extraction_collides(const fs::path& entry_path, const std::string& entry_package) +{ + if (!is_valid_entry_package(entry_package)) + return false; + + // Mirror add_wheel_dependencies_to_sys_path(): it scans the entry's parent directory (or the + // entry path itself when it has no extension) and recognizes wheel files by extension in any + // case. Keep the same rules here so this guard protects exactly the directories that loader + // uses. + const fs::path plugin_dir = entry_path.has_extension() ? entry_path.parent_path() : entry_path; + const fs::path io_plugin_dir = extended_path(plugin_dir); + const fs::path io_entry_path = extended_path(entry_path); + boost::system::error_code ec; + if (!fs::is_directory(io_plugin_dir, ec)) + return false; + + for (fs::directory_iterator it(io_plugin_dir, ec); !ec && it != fs::directory_iterator(); ++it) { + if (!fs::is_regular_file(it->status())) + continue; + + const fs::path candidate = it->path(); + if (candidate == io_entry_path) + continue; + if (!has_wheel_extension(candidate)) + continue; + + if (names_equal_case_insensitive(candidate.stem().string(), entry_package)) + return true; + } + return false; +} + +bool entry_package_present(const fs::path& target, const std::string& entry_package) +{ + if (!is_valid_entry_package(entry_package)) + return false; + + // The target is the wheel cache directory, which sits below the plugin folder and is the path + // most likely to pass MAX_PATH, so every probe here uses its extended-length form. + const fs::path io_target = extended_path(target); + + // Dotted import names ("pkg.sub") map onto nested components; the wheel installs + // top-level distributions, so this is only a sanity check that the root exists. + fs::path relative; + std::string component; + for (char ch : entry_package) { + if (ch == '.') { + relative /= component; + component.clear(); + } else { + component += ch; + } + } + relative /= component; + + if (fs::is_directory(io_target / relative)) + return true; + if (fs::is_regular_file(io_target / relative.parent_path() / (relative.filename().string() + ".py"))) + return true; + + // A compiled top-level module (.cpython-312-x86_64-linux-gnu.so / .pyd). + const fs::path parent = io_target / relative.parent_path(); + if (fs::is_directory(parent)) { + const std::string leaf = relative.filename().string() + "."; + for (fs::directory_iterator it(parent); it != fs::directory_iterator(); ++it) { + if (!fs::is_regular_file(it->status())) + continue; + const std::string filename = it->path().filename().string(); + if (filename.rfind(leaf, 0) != 0) + continue; + const std::string ext = it->path().extension().string(); + if (ext == ".so" || ext == ".pyd" || ext == ".dll") + return true; + } + } + + return false; +} + +// True when /__whl_extracted__/ is a markerless pre-uv extraction that +// already contains the entry package. Such a target is importable through the ordinary directory +// import, so it is used directly instead of being reinstalled. A marker, even an invalid one, makes +// the directory a uv-managed target whose reuse/reinstall decision belongs to is_installed(). +// Only the entry package's own directory is inspected; the shared __whl_extracted__/ parent also +// holds dependency extractions. +bool has_legacy_entry_extraction(const PluginDescriptor& descriptor) +{ + if (!is_valid_entry_package(descriptor.entry_package)) + return false; + + const std::string target_path = install_dir(descriptor.plugin_root, descriptor.entry_package); + if (target_path.empty()) + return false; + + // The cache target is the path MAX_PATH is reached first, so probe it in extended form. + const fs::path target = extended_path(fs::path(target_path)); + boost::system::error_code ec; + if (!fs::is_directory(target, ec)) + return false; + + ec.clear(); + const bool marker_present = fs::exists(target / MARKER_FILE_NAME, ec); + // Boost's exists() reports an absent path through ec as not-found; that is marker absence. + // Only a different error means the marker's presence could not be determined. + if (ec && ec != boost::system::errc::no_such_file_or_directory) + return false; + if (marker_present) + return false; + + return entry_package_present(target, descriptor.entry_package); +} + +// 64-bit FNV-1a over the wheel bytes. The marker only needs to detect a changed file; this is a +// cache hint, not a trust decision. +bool fingerprint_file(const fs::path& path, std::string& fingerprint, std::uint64_t& size, std::string& error) +{ + boost::nowide::ifstream file(io_path_string(path), std::ios::binary); + if (!file) { + error = "Failed to read plugin wheel: " + path.string(); + return false; + } + + std::uint64_t hash = 1469598103934665603ULL; + std::uint64_t total = 0; + char buffer[64 * 1024]; + while (file) { + file.read(buffer, sizeof(buffer)); + const std::streamsize read = file.gcount(); + for (std::streamsize i = 0; i < read; ++i) { + hash ^= static_cast(buffer[i]); + hash *= 1099511628211ULL; + } + total += static_cast(read); + } + if (file.bad()) { + error = "Failed to read plugin wheel: " + path.string(); + return false; + } + + char hex[17]; + std::snprintf(hex, sizeof(hex), "%016llx", static_cast(hash)); + fingerprint = hex; + size = total; + return true; +} + +void remove_tree_quietly(const fs::path& path) +{ + boost::system::error_code ec; + fs::remove_all(extended_path(path), ec); + if (ec) + BOOST_LOG_TRIVIAL(warning) << "Failed to remove plugin wheel installation directory " << path.string() << ": " << ec.message(); +} + +// Only staging directories are disposable. A `__wheel_prev__-*` directory can be the last usable +// target when a promotion failed and the restore failed; it is removed after a successful +// promotion, never guessed at by a later scan. +bool is_install_scratch_dir(const fs::path& path) +{ + return path.filename().string().rfind(STAGING_DIR_PREFIX, 0) == 0; +} + +// Drop staging leftovers from an interrupted install. Discovery ignores them; they are only disk +// noise. Best effort: a failure to remove one is logged, not fatal. +void remove_stale_scratch_dirs(const fs::path& plugin_root) +{ + const fs::path io_plugin_root = extended_path(plugin_root); + boost::system::error_code ec; + if (!fs::is_directory(io_plugin_root, ec)) + return; + + std::vector stale; + for (fs::directory_iterator it(io_plugin_root, ec); !ec && it != fs::directory_iterator(); ++it) { + // Rebuild the entry from the plain plugin root so the paths handed to cleanup, and the + // paths it logs, keep their normal form. + if (is_install_scratch_dir(it->path())) + stale.push_back(plugin_root / it->path().filename()); + } + for (const fs::path& path : stale) + remove_tree_quietly(path); +} + +bool default_uv_runner(const std::vector& args, std::chrono::seconds timeout, std::string& error) +{ + return PythonInterpreter::run_uv(args, timeout, error); +} + +} // namespace + +bool is_valid_wheel_filename(const std::string& filename) +{ + constexpr const char* extension = ".whl"; + constexpr std::size_t extension_length = 4; + + if (filename.size() <= extension_length) + return false; + if (filename.compare(filename.size() - extension_length, extension_length, extension) != 0) + return false; + + const std::string stem = filename.substr(0, filename.size() - extension_length); + const std::vector parts = split_tag(stem); + if (parts.size() != 5 && parts.size() != 6) + return false; + + for (std::size_t i = 0; i < parts.size(); ++i) { + const std::string& part = parts[i]; + if (part.empty()) + return false; + if (std::any_of(part.begin(), part.end(), [i](char ch) { return !is_tag_char(ch) && !(i == 1 && ch == '!'); })) + return false; + } + + // A PEP 440 version starts with a digit; the three trailing components are python, ABI and + // platform tags. + if (!std::isdigit(static_cast(parts[1][0]))) + return false; + + const std::size_t tag_offset = parts.size() == 6 ? 3 : 2; + return looks_like_wheel_tags(parts[tag_offset], parts[tag_offset + 1], parts[tag_offset + 2]); +} + +std::string make_wheel_filename(const std::string& name, const std::string& version, const std::string& tag) +{ + const std::string escaped_name = escape_wheel_component(name, "_"); + const std::string escaped_version = escape_wheel_component(version, "+!"); + if (escaped_name.empty() || escaped_version.empty() || tag.empty()) + return {}; + + // `tag` is the triple "python-abi-platform" from the WHEEL file, so it legitimately contains + // the two '-' separators that join the filename components. Validate it as a triple here; + // is_valid_wheel_filename() below applies the per-component character and tag-plausibility + // rules to the assembled name. + const std::vector tag_parts = split_tag(tag); + if (tag_parts.size() != 3) + return {}; + + const std::string filename = escaped_name + "-" + escaped_version + "-" + tag + ".whl"; + return is_valid_wheel_filename(filename) ? filename : std::string{}; +} + +namespace { + +// Parse a CPython-style tag ("cp312", "cp38") into major/minor. A tag with only a major digit +// ("cp3") reports minor == -1, meaning "any minor of that major". +bool parse_cpython_tag(const std::string& tag, int& major, int& minor) +{ + if (tag.size() < 3 || tag.compare(0, 2, "cp") != 0) + return false; + + std::size_t end = 2; + while (end < tag.size() && std::isdigit(static_cast(tag[end])) != 0) + ++end; + if (end == 2) + return false; + + major = tag[2] - '0'; + minor = -1; + if (end > 3) { + int value = 0; + for (std::size_t i = 3; i < end; ++i) { + if (value > 100000) + return false; + value = value * 10 + (tag[i] - '0'); + } + minor = value; + } + return true; +} + +// True when a declared python tag (py3, py3.12, py2.py3, cp312, ...) can run on the bundled +// interpreter. PyPy tags (pp*) cannot. +bool python_tag_compatible(const std::string& python_tag, int major, int minor) +{ + std::size_t start = 0; + while (start <= python_tag.size()) { + const std::size_t dot = python_tag.find('.', start); + const std::string component = python_tag.substr(start, dot == std::string::npos ? std::string::npos : dot - start); + + if (component.compare(0, 2, "py") == 0 && component.size() > 2) { + bool only_digits = true; + for (std::size_t i = 2; i < component.size(); ++i) { + if (std::isdigit(static_cast(component[i])) == 0) { + only_digits = false; + break; + } + } + if (only_digits) { + const int component_major = component[2] - '0'; + int component_minor = 0; + for (std::size_t i = 3; i < component.size(); ++i) + component_minor = component_minor * 10 + (component[i] - '0'); + if (component_major == major && (component.size() == 3 || component_minor <= minor)) + return true; + } + } else if (component.compare(0, 2, "cp") == 0) { + int tag_major = 0, tag_minor = -1; + if (parse_cpython_tag(component, tag_major, tag_minor) && tag_major == major && + (tag_minor < 0 || tag_minor <= minor)) + return true; + } + + if (dot == std::string::npos) + break; + start = dot + 1; + } + return false; +} + +// True when the declared ABI can be loaded by the bundled CPython. Pure wheels ("none") follow the +// python tag; "abi3" is the stable ABI up to the running minor; a concrete cpXY ABI must match. +// This is interpreter compatibility only: platform/architecture remains uv's decision. +bool abi_compatible(const std::string& python_tag, + const std::string& abi, + int major, + int minor, + const std::string& current_abi) +{ + if (abi == "none") + return python_tag_compatible(python_tag, major, minor); + + if (abi == "abi3") { + int tag_major = 0, tag_minor = -1; + return parse_cpython_tag(python_tag, tag_major, tag_minor) && tag_major == major && tag_minor <= minor; + } + + if (abi.compare(0, 2, "cp") == 0) + return abi == current_abi && python_tag_compatible(python_tag, major, minor); + + return false; +} + +} // namespace + +std::string wheel_filename_tag(const std::vector& tags) +{ + struct TagParts + { + std::string python; + std::string abi; + std::string platform; + }; + + std::vector valid; + for (const std::string& tag : tags) { + const std::vector parts = split_tag(tag); + if (parts.size() != 3 || parts[0].empty() || parts[1].empty() || parts[2].empty()) + continue; + if (!looks_like_wheel_tags(parts[0], parts[1], parts[2])) + continue; + valid.push_back({parts[0], parts[1], parts[2]}); + } + + if (valid.empty()) + return {}; + + // Prefer a tag the bundled interpreter can actually run. This is only a selection among the + // tags the wheel declares; it never changes one. If no declared tag is interpreter-compatible, + // keep the declared tags so uv can report the incompatibility clearly. + std::vector compatible; + { + const std::string current_abi = PythonInterpreter::python_abi_tag(); + int major = 0, minor = 0; + if (parse_cpython_tag(current_abi, major, minor)) { + for (const TagParts& tag : valid) { + if (abi_compatible(tag.python, tag.abi, major, minor, current_abi)) + compatible.push_back(tag); + } + } + } + const std::vector& candidates = compatible.empty() ? valid : compatible; + + // A declared universal tag covers every platform; prefer it over a platform-specific one. + for (const TagParts& tag : candidates) { + if (tag.platform == "any") + return tag.python + "-" + tag.abi + "-any"; + } + + const TagParts& first = candidates.front(); + + // Only combine tags that differ in nothing but a simple platform. Anything else (a different + // interpreter or ABI tag, or an already-compressed platform) is left exactly as the wheel + // declared it; uv decides whether the resulting filename is usable. + for (const TagParts& tag : candidates) { + if (tag.python != first.python || tag.abi != first.abi) + return first.python + "-" + first.abi + "-" + first.platform; + if (tag.platform.find('.') != std::string::npos) + return first.python + "-" + first.abi + "-" + first.platform; + } + + std::vector platforms; + for (const TagParts& tag : candidates) { + if (std::find(platforms.begin(), platforms.end(), tag.platform) == platforms.end()) + platforms.push_back(tag.platform); + } + + // A single tag, or a set that cannot be expressed as platform alternatives: keep the first tag. + if (platforms.size() <= 1) + return first.python + "-" + first.abi + "-" + first.platform; + + // PEP 425 compressed tag set: one python/abi with alternative platforms. + std::string platform = platforms.front(); + for (std::size_t i = 1; i < platforms.size(); ++i) + platform += "." + platforms[i]; + return first.python + "-" + first.abi + "-" + platform; +} + +bool is_valid_entry_package(const std::string& entry_package) +{ + if (entry_package.empty()) + return false; + + bool component_has_char = false; + for (unsigned char ch : entry_package) { + if (ch == '.') { + // Dotted names need non-empty components; this also rejects "." and "..". + if (!component_has_char) + return false; + component_has_char = false; + } else { + if (!is_safe_package_path_char(ch)) + return false; + component_has_char = true; + } + } + return component_has_char; +} + +std::string install_dir(const std::string& plugin_root, const std::string& entry_package) +{ + if (!is_valid_entry_package(entry_package)) + return {}; + return (fs::path(plugin_root) / EXTRACTED_DIR_NAME / entry_package).string(); +} + +bool delete_install_cache(const boost::filesystem::path& plugin_root, std::string& error) +{ + boost::system::error_code ec; + fs::remove_all(extended_path(plugin_root / EXTRACTED_DIR_NAME), ec); + if (ec) { + // TRN %1% is the system error message. + error = GUI::format(_u8L("Failed to clear plugin cache: %1%"), ec.message()); + return false; + } + return true; +} + +bool is_installed(const PluginDescriptor& descriptor) +{ + if (descriptor.plugin_root.empty()) + return false; + if (descriptor.entry_path.empty()) + return false; + if (descriptor.entry_package.empty()) + return false; + if (!is_valid_entry_package(descriptor.entry_package)) + return false; + + // The installed target is the path most likely to pass MAX_PATH, so it is probed and read in + // extended-length form. Only local path objects carry the prefix; marker fields and the + // descriptor's paths stay unprefixed. + const fs::path target = extended_path(fs::path(install_dir(descriptor.plugin_root, descriptor.entry_package))); + if (!fs::is_directory(target)) + return false; + + const fs::path marker_path = target / MARKER_FILE_NAME; + if (!fs::is_regular_file(marker_path)) + return false; + + nlohmann::json marker; + { + boost::nowide::ifstream file(io_path_string(marker_path)); + if (!file) + return false; + marker = nlohmann::json::parse(file, nullptr, false, true); + } + if (marker.is_discarded() || !marker.is_object()) + return false; + + const auto int_field = [&marker](const char* key) -> long long { + return marker.contains(key) && marker[key].is_number_integer() ? marker[key].get() : -1; + }; + const auto size_field = [&marker](const char* key, std::uint64_t& out) -> bool { + if (!marker.contains(key) || !marker[key].is_number_integer()) + return false; + if (marker[key].is_number_unsigned()) { + out = marker[key].get(); + return true; + } + const auto value = marker[key].get(); + if (value < 0) + return false; + out = static_cast(value); + return true; + }; + const auto string_field = [&marker](const char* key) -> std::string { + return marker.contains(key) && marker[key].is_string() ? marker[key].get() : std::string{}; + }; + + if (int_field("format") != INSTALL_FORMAT) + return false; + if (string_field("abi") != PythonInterpreter::python_abi_tag()) + return false; + if (string_field("entry_package") != descriptor.entry_package) + return false; + + std::string fingerprint; + std::uint64_t size = 0; + std::string fingerprint_error; + if (!fingerprint_file(descriptor.entry_path, fingerprint, size, fingerprint_error)) + return false; + + std::uint64_t recorded_size = 0; + if (!size_field("size", recorded_size)) + return false; + if (string_field("fingerprint") != fingerprint || recorded_size != size) + return false; + + if (!entry_package_present(target, descriptor.entry_package)) + return false; + + return true; +} + +bool ensure_installed(const PluginDescriptor& descriptor, std::string& error, const UvRunner& runner) +{ + error.clear(); + + if (descriptor.plugin_root.empty()) { + error = "Plugin has no installation directory."; + return false; + } + if (descriptor.entry_path.empty()) { + error = "Plugin has no entry file."; + return false; + } + if (!has_wheel_extension(descriptor.entry_path)) { + error = "uv wheel installation is only available for .whl plugins."; + return false; + } + if (!descriptor.is_metadata_valid()) { + error = "Plugin metadata is invalid; its wheel cannot be installed."; + return false; + } + if (descriptor.entry_package.empty()) { + error = "Wheel does not identify an importable entry package."; + return false; + } + if (!is_valid_entry_package(descriptor.entry_package)) { + error = "Wheel entry package '" + descriptor.entry_package + "' is not a safe package path."; + return false; + } + + const fs::path plugin_root = fs::path(descriptor.plugin_root); + const fs::path entry = fs::path(descriptor.entry_path); + const std::string target_path = install_dir(descriptor.plugin_root, descriptor.entry_package); + const fs::path target(target_path); + + // Every filesystem step below runs on the extended-length form: the staging root and the + // installed cache sit below the plugin folder and are where MAX_PATH is reached first. The + // plain paths stay for messages and for the uv arguments (see below). + const fs::path io_entry = extended_path(entry); + const fs::path io_target = extended_path(target); + + // __whl_extracted__/ is shared with dependency extractions. Never take over a directory that + // belongs to a dependency wheel: the two would fight over the same directory and import name. + // Checked before reuse so a marker in a coincidentally named dependency directory cannot make + // the entry look installed. + if (dependency_extraction_collides(entry, descriptor.entry_package)) { + error = "Wheel entry package '" + descriptor.entry_package + + "' collides with the extraction directory of a dependency wheel next to the entry; " + "rename the dependency wheel so its extraction uses a different directory."; + return false; + } + + if (is_installed(descriptor)) { + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] reusing installation for " << descriptor.plugin_key << " (" + << target_path << ")"; + return true; + } + + // Wheel installs mutate a per-plugin directory; serialize them so two plugin loads cannot + // interleave staging/promotion (load already serializes, this also covers direct callers). + static std::mutex install_mutex; + std::lock_guard install_lock(install_mutex); + + // Another caller may have completed the same install while this one waited. + if (is_installed(descriptor)) { + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] reusing installation for " << descriptor.plugin_key << " (" + << target_path << ")"; + return true; + } + + // A markerless entry-specific directory that already contains the entry package is the pre-uv + // loader's extraction. It is imported through the same directory path, so accept it without + // running uv. Checked under the same lock as installation: a concurrent load cannot observe a + // target that another caller is replacing. A marker-present target is uv-managed and keeps the + // reinstall path above, so a stale or invalid uv installation is still rebuilt. + if (has_legacy_entry_extraction(descriptor)) { + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] reusing legacy extraction for " << descriptor.plugin_key << " (" + << target_path << ")"; + return true; + } + + std::string staged_name = entry.filename().string(); + if (!is_valid_wheel_filename(staged_name)) { + // uv accepts only the lowercase ".whl" extension. A stored wheel with an uppercase + // extension keeps its name on disk; only the staged input copy is normalized. + const std::string normalized_name = entry.stem().string() + ".whl"; + if (is_valid_wheel_filename(normalized_name)) { + staged_name = normalized_name; + } else { + // Cloud downloads and side-loaded wheels can carry names uv rejects. Stage a copy + // under a name derived from the wheel's own metadata; the stored wheel is left + // untouched. + WheelInstallMetadata metadata; + std::string metadata_error; + if (!read_wheel_install_metadata(entry, metadata, metadata_error)) { + error = "Failed to read wheel metadata for installation: " + metadata_error; + return false; + } + + const std::string tag = wheel_filename_tag(metadata.tags); + if (tag.empty()) { + error = "Wheel " + entry.filename().string() + + " has no usable filename tag and declares no well-formed python-abi-platform tag in its WHEEL file."; + return false; + } + staged_name = make_wheel_filename(metadata.name, metadata.version, tag); + if (staged_name.empty()) { + error = "Cannot build a valid wheel filename from the metadata of " + entry.filename().string() + "."; + return false; + } + } + } + + remove_stale_scratch_dirs(plugin_root); + + boost::system::error_code ec; + const std::string unique = fs::unique_path("%%%%-%%%%-%%%%").string(); + const fs::path staging_root = plugin_root / (std::string(STAGING_DIR_PREFIX) + unique); + const fs::path staging_input = staging_root / "input"; + const fs::path staging_target = staging_root / "target"; + const fs::path io_staging_input = extended_path(staging_input); + const fs::path io_staging_target = extended_path(staging_target); + + auto fail = [&error, &staging_root](const std::string& message) { + remove_tree_quietly(staging_root); + error = message; + return false; + }; + + fs::create_directories(io_staging_input, ec); + if (ec) + return fail("Failed to create wheel staging directory " + staging_input.string() + ": " + ec.message()); + + const fs::path staged_wheel = staging_input / staged_name; + fs::copy_file(io_entry, extended_path(staged_wheel), ec); + if (ec) + return fail("Failed to stage plugin wheel " + entry.string() + ": " + ec.message()); + + const std::string python_executable = PythonInterpreter::bundled_python_executable(); + if (python_executable.empty()) + return fail("Bundled Python executable not found. Plugin wheel installation is unavailable."); + + // uv receives the plain absolute paths, not the extended-length form: uv is a Rust program whose + // standard library qualifies and verbatim-prefixes a long path itself, and a "\\?\" argument + // would change how it interprets the path. Only this process's own filesystem calls need the + // prefix. + const std::vector args = {"--no-config", + "pip", + "install", + "--python", + python_executable, + "--no-python-downloads", + "--no-deps", + "--no-index", + "--no-cache", + "--link-mode", + "copy", + "--target", + staging_target.string(), + staged_wheel.string()}; + + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] installing " << staged_name << " for " << descriptor.plugin_key + << " into " << staging_target.string(); + + const UvRunner uv_runner = runner ? runner : UvRunner(default_uv_runner); + std::string uv_error; + if (!uv_runner(args, INSTALL_TIMEOUT, uv_error)) { + if (uv_error.empty()) + uv_error = "uv pip install failed"; + return fail(uv_error); + } + + if (!fs::is_directory(io_staging_target, ec)) + return fail("uv reported success but did not create the plugin target."); + if (!entry_package_present(staging_target, descriptor.entry_package)) + return fail("uv reported success but did not install the entry package '" + descriptor.entry_package + "'."); + + std::string fingerprint; + std::uint64_t wheel_size = 0; + std::string fingerprint_error; + if (!fingerprint_file(entry, fingerprint, wheel_size, fingerprint_error)) + return fail(fingerprint_error); + + { + nlohmann::json marker; + marker["format"] = INSTALL_FORMAT; + marker["size"] = wheel_size; + marker["fingerprint"] = fingerprint; + marker["abi"] = PythonInterpreter::python_abi_tag(); + marker["entry_package"] = descriptor.entry_package; + + boost::nowide::ofstream file(io_path_string(io_staging_target / MARKER_FILE_NAME)); + if (!file) + return fail("Failed to write the wheel installation marker."); + file << marker.dump(2, ' ', false, nlohmann::json::error_handler_t::replace); + if (!file) + return fail("Failed to write the wheel installation marker."); + } + + // Promote only a complete target. The previous target is retired under a name discovery + // ignores and is restored if promotion fails; it is never deleted before the new one is live. + // The target's parent (__whl_extracted__) also holds dependency extractions, so creating it is + // safe; only the entry package's own subdirectory is replaced. + ec.clear(); + fs::create_directories(io_target.parent_path(), ec); + if (ec) + return fail("Failed to create the plugin wheel extraction directory " + target.parent_path().string() + + ": " + ec.message()); + + const fs::path previous = plugin_root / (std::string(PREVIOUS_DIR_PREFIX) + unique); + const fs::path io_previous = extended_path(previous); + ec.clear(); + const bool had_target = fs::exists(io_target, ec); + // Boost's exists() reports an absent path through ec as not-found; a fresh install legitimately + // has no target. Only a different error means the probe itself failed. + if (ec && ec != boost::system::errc::no_such_file_or_directory) + return fail("Failed to inspect the existing wheel installation target: " + ec.message()); + if (had_target) { + fs::rename(io_target, io_previous, ec); + if (ec) { + std::string message = "Failed to move the previous wheel installation aside: " + ec.message(); + remove_tree_quietly(staging_root); + error = std::move(message); + return false; + } + } + + fs::rename(io_staging_target, io_target, ec); + if (ec) { + std::string message = "Failed to activate the new wheel installation: " + ec.message(); + if (had_target) { + boost::system::error_code restore_ec; + fs::rename(io_previous, io_target, restore_ec); + if (restore_ec) { + // Keep the retired target: it may still be the only usable copy. + message += " The previous installation could not be restored and was kept at " + previous.string() + ": " + + restore_ec.message(); + } + } + remove_tree_quietly(staging_root); + error = std::move(message); + return false; + } + + // staging_target moved into place; this removes the input copy and the empty staging wrapper. + remove_tree_quietly(staging_root); + + if (had_target) + remove_tree_quietly(previous); + + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] installed " << entry.filename().string() << " for " + << descriptor.plugin_key << " into " << target.string(); + return true; +} + +} // namespace Slic3r::plugin_wheel_install diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index add3887a2a..40a03de7f6 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -4,6 +4,8 @@ #include +#include +#include #include #include #include @@ -128,6 +130,21 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD // Returns true on success. bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error); +// The subset of wheel metadata uv needs to accept a staged copy under a valid filename: the +// distribution name and version from METADATA and the declared WHEEL Tag lines. +struct WheelInstallMetadata +{ + std::string name; + std::string version; + std::vector tags; +}; +bool read_wheel_install_metadata(const boost::filesystem::path& whl_path, WheelInstallMetadata& out, std::string& error); + +// True when the path carries the wheel package extension, compared case-insensitively: a package +// stored on a case-insensitive filesystem can end in ".WHL". Only uv requires the lower-case +// spelling for the file it is handed, so the staged copy is normalized instead of rejecting it. +bool has_wheel_extension(const boost::filesystem::path& path); + // Find the single plugin entry file (.py or .whl) in a directory. // Ignores __whl_extracted__ and hidden files/dirs. // Returns the path to the entry file, or an empty path with error set if zero or multiple candidates. @@ -202,3 +219,79 @@ bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescrip bool read_install_state(const boost::filesystem::path& plugin_dir, PluginInstallState& out); } // namespace Slic3r + +// uv-based installation of a wheel plugin's entry wheel. +namespace Slic3r::plugin_wheel_install { + +// Shared wheel extraction root inside the plugin root. Dependency wheels are extracted into it, +// and the entry wheel is installed into /. This is the same path +// the pre-uv loader extracted the entry wheel to, so there is one cache location. The "__" prefix +// keeps discovery from treating it as a plugin package (see is_ignored_plugin_directory()). +inline constexpr const char* EXTRACTED_DIR_NAME = "__whl_extracted__"; + +// Staging and retirement directories, also inside the plugin root and ignored by discovery. +inline constexpr const char* STAGING_DIR_PREFIX = "__wheel_staging__-"; +inline constexpr const char* PREVIOUS_DIR_PREFIX = "__wheel_prev__-"; + +// Marker written into the target before it is promoted. Bump INSTALL_FORMAT when the layout or +// the uv invocation changes, so an existing target is rebuilt instead of reused. +inline constexpr const char* MARKER_FILE_NAME = "__wheel_install__.json"; +inline constexpr int INSTALL_FORMAT = 2; + +inline constexpr std::chrono::seconds INSTALL_TIMEOUT{120}; + +// Runs `uv ` and reports success. Injectable so tests can exercise staging, promotion and +// reuse without a real uv binary. +using UvRunner = std::function& args, std::chrono::seconds timeout, std::string& error)>; + +// True for a filename shaped like a PEP 427 wheel: name-version(-build)?-python-abi-platform.whl, +// where the three trailing components look like real interpreter/ABI/platform tags. uv performs +// the full metadata and compatibility validation; this only decides whether the stored name can be +// handed to uv as-is or a metadata-derived copy has to be staged. +bool is_valid_wheel_filename(const std::string& filename); + +// Build a PEP 427 wheel filename from metadata. Returns an empty string when any component is +// empty or cannot be escaped into the allowed character set. +std::string make_wheel_filename(const std::string& name, const std::string& version, const std::string& tag); + +// Return a python-abi-platform tag for a staged wheel filename from the tags the wheel declares. +// A declared tag compatible with the bundled interpreter is preferred (so a wheel declaring both +// py2 and py3 uses py3); this never invents a tag. Among the chosen tags, simple platform +// alternatives are combined into one PEP 425 compressed tag set. uv performs the final +// platform/architecture compatibility check. Empty when no well-formed tag exists. +std::string wheel_filename_tag(const std::vector& tags); + +// True for a safe dotted package path: non-empty components separated by '.', with no ASCII path +// separators, control characters, or characters Windows forbids in filenames. Bytes >= 0x80 are +// allowed, so non-ASCII (Unicode) import names are not rejected. This is path-component safety, +// not a Python identifier check; an unimportable name is reported when the module is imported. +bool is_valid_entry_package(const std::string& entry_package); + +// Path of the installed target: /__whl_extracted__/. Does not touch +// the disk. Empty when entry_package is not a safe import name. +std::string install_dir(const std::string& plugin_root, const std::string& entry_package); + +// True when the target exists and the marker proves it was installed from the current entry wheel +// for this interpreter and entry package. +bool is_installed(const PluginDescriptor& descriptor); + +// Delete the plugin's installed-wheel cache (the whole __whl_extracted__ subtree). The plugin root +// must already have passed resolve_allowed_plugin_root(): this only removes the cache directory, +// never the plugin root, the stored wheel or the install sidecar. Removal uses the extended-length +// form, so a cache whose own root passes MAX_PATH is still cleared on Windows. On failure `error` +// explains the cause. +bool delete_install_cache(const boost::filesystem::path& plugin_root, std::string& error); + +// Install the plugin's entry wheel with uv into the legacy extraction path +// /__whl_extracted__/ unless a matching installation already exists. +// An existing markerless directory there is a pre-uv extraction: when it already contains the entry +// package it is used directly, without running uv. A markerless target without the entry package, +// and a target whose marker is stale or invalid, is replaced. Directories for dependency wheels +// elsewhere under __whl_extracted__/ are never touched; a dependency whose filename stem equals the +// entry package is reported as a collision instead of being replaced. The wheel is installed to a +// fresh staging target and promoted only after a successful, complete installation; the previous +// target is restored on failure. On failure `error` explains the cause and no partial target is +// importable. +bool ensure_installed(const PluginDescriptor& descriptor, std::string& error, const UvRunner& runner = {}); + +} // namespace Slic3r::plugin_wheel_install diff --git a/src/slic3r/plugin/PluginLoader.cpp b/src/slic3r/plugin/PluginLoader.cpp index a324f389aa..06aa7a3f2e 100644 --- a/src/slic3r/plugin/PluginLoader.cpp +++ b/src/slic3r/plugin/PluginLoader.cpp @@ -23,15 +23,14 @@ #include #include #include -#include #include "slic3r/plugin/PluginDescriptor.hpp" #include +#include #include #include #include "slic3r/plugin/PythonPluginInterface.hpp" #include #include -#include #include #include @@ -148,6 +147,15 @@ void teardown_capabilities(std::vector& plugin_paths, @@ -155,35 +163,57 @@ bool add_wheel_dependencies_to_sys_path(const PluginDescriptor& descriptor, { namespace fs = boost::filesystem; - const fs::path entry_path(descriptor.entry_path); - const fs::path plugin_dir = entry_path.has_extension() ? entry_path.parent_path() : entry_path; - if (!fs::exists(plugin_dir) || !fs::is_directory(plugin_dir)) + // The plugin folder, and every cache directory below it, can pass the legacy Windows + // MAX_PATH, where the plain spelling cannot be probed at all. Each probe below therefore + // falls back to the extended-length form (the identity off Windows), and only keeps it where + // the plain spelling failed: those paths are what a plugin then sees as __file__ and sys.path + // and what the host compares against the plain plugin root, so an install that resolves + // plainly keeps the plain path it had before. + const fs::path plain_entry_path(descriptor.entry_path); + const fs::path plain_plugin_dir = plain_entry_path.has_extension() ? plain_entry_path.parent_path() : plain_entry_path; + + // Walk the folder through whichever spelling reaches it; an install that fits uses the plain + // one, as before. + const bool plain_reachable = plain_path_exists(plain_plugin_dir); + const fs::path entry_path = plain_reachable ? plain_entry_path : extended_path(plain_entry_path); + const fs::path scan_dir = plain_reachable ? plain_plugin_dir : extended_path(plain_plugin_dir); + + boost::system::error_code scan_ec; + if (!fs::is_directory(scan_dir, scan_ec) || scan_ec) return true; PythonInterpreter& interpreter = PythonInterpreter::instance(); - for (fs::directory_iterator it(plugin_dir); it != fs::directory_iterator(); ++it) { - if (!fs::is_regular_file(it->status()) || it->path().extension() != ".whl") + for (fs::directory_iterator it(scan_dir); it != fs::directory_iterator(); ++it) { + if (!fs::is_regular_file(it->status()) || !has_wheel_extension(it->path())) continue; - // Skip the entry file itself — it is loaded by its own path. + // Skip the entry file itself — it is loaded by its own path. Both sides carry the same + // spelling, so the comparison holds in the extended form too. if (it->path() == entry_path) continue; - const fs::path dep_dir = plugin_dir / "__whl_extracted__" / it->path().stem().string(); - if (!fs::exists(dep_dir)) { + // Build from the plain folder so the recorded spelling stays plain whenever it can. + const fs::path plain_dep_dir = plain_plugin_dir / plugin_wheel_install::EXTRACTED_DIR_NAME / it->path().stem().string(); + const fs::path io_dep_dir = extended_path(plain_dep_dir); + if (!plain_path_exists(plain_dep_dir) && !plain_path_exists(io_dep_dir)) { std::string extract_error; - if (!extract_zip_to_directory(it->path(), dep_dir, extract_error)) { + if (!extract_zip_to_directory(it->path(), plain_dep_dir, extract_error)) { // TRN %1% is the dependency file, %2% the error detail. - error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"), it->path().string(), extract_error); + error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"), + (plain_plugin_dir / it->path().filename()).string(), extract_error); return false; } } - std::string syspath_error; - if (!interpreter.add_plugin_sys_path(dep_dir.string(), syspath_error)) { + // The string handed to the interpreter is the one recorded for unload, so the sys.path + // entry is removed by the same key. Re-probe after extraction: a first extraction through + // a path that fits resolves plainly and must keep that spelling. + const std::string dep_path = plain_path_exists(plain_dep_dir) ? plain_dep_dir.string() : io_dep_dir.string(); + std::string syspath_error; + if (!interpreter.add_plugin_sys_path(dep_path, syspath_error)) { error = GUI::format(_u8L("Failed to add .whl dependency to sys.path: %1%"), syspath_error); return false; } - plugin_paths.push_back(dep_dir.string()); + plugin_paths.push_back(dep_path); } return true; @@ -199,12 +229,13 @@ PyObject* import_plugin_module(const PluginDescriptor& descriptor, if (descriptor.entry_package.empty()) return interpreter.load_module_from_file(descriptor.entry_path, error, &plugin_paths, &plugin_modules); - if (boost::filesystem::path(descriptor.entry_path).extension() == ".whl") - return interpreter.load_module_from_whl( - descriptor.entry_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules); + // A wheel entry is imported from the directory its installation lives in; a .py entry in place. + const std::string dir_path = has_wheel_extension(descriptor.entry_path) ? + plugin_wheel_install::install_dir(descriptor.plugin_root, descriptor.entry_package) : + descriptor.entry_path; return interpreter.load_module_from_directory( - descriptor.entry_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules); + dir_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules); } std::string plugin_module_name(const PluginDescriptor& descriptor) @@ -291,6 +322,22 @@ bool load(const PluginDescriptor& descriptor, plugin.descriptor = descriptor; plugin.module_name = plugin_module_name(descriptor); + // Wheel entries have one installation and one loading path: uv installs the entry wheel into + // the legacy extraction path, then the entry package is imported from there. An existing + // markerless extraction at that path is a pre-uv cache and is used directly when it contains + // the entry package. Dependency wheels are extracted alongside it under __whl_extracted__/ + // and are not touched. + const bool has_entry_wheel = plugin_package_extension(descriptor.entry_path) == ".whl"; + if (has_entry_wheel) { + std::string wheel_install_error; + if (!plugin_wheel_install::ensure_installed(descriptor, wheel_install_error)) { + // Report the failure instead of silently falling back to extraction. + // TRN %1% is the uv/installation error detail. + error = GUI::format(_u8L("Failed to install plugin wheel: %1%"), wheel_install_error); + return false; + } + } + if (!skip_deps) { std::string pkg_install_error; if (!install_packages(descriptor.dependencies, pkg_install_error)) { @@ -510,12 +557,6 @@ bool install_packages(const std::vector& pkgs, std::string& error) if (pkgs.empty()) return true; - const std::string uv_path = PythonInterpreter::bundled_uv_path(); - if (uv_path.empty()) { - error = "Bundled uv executable not found. Python package installation is unavailable."; - return false; - } - const std::string python_executable = PythonInterpreter::bundled_python_executable(); if (python_executable.empty()) { error = "Bundled Python executable not found. Python package installation is unavailable."; @@ -538,81 +579,7 @@ bool install_packages(const std::vector& pkgs, std::string& error) BOOST_LOG_TRIVIAL(info) << "Installing Python packages via uv for " << python_executable << ": " << boost::algorithm::join(pkgs, ", "); - try { - namespace process = boost::process; - - process::ipstream std_err; - process::child child(uv_path, process::args(args), -#ifdef _WIN32 - // uv.exe (and the python.exe it spawns) are console-subsystem programs. - // OrcaSlicer is a GUI app with no console of its own, so without this flag - // Windows allocates a fresh console window for the child that flashes on - // screen during startup plugin loading. Matches ProcessRunner/MediaPlayCtrl. - process::windows::create_no_window, -#endif - process::std_err > std_err); - - std::string err_output; - std::thread stderr_reader([&std_err, &err_output]() { - std::string line; - while (std::getline(std_err, line)) { - err_output += line + '\n'; - } - }); - - // Wait up to 120 seconds for package install to complete. - // - // NOTE: we poll child.running() instead of calling child.wait_for(). - // On macOS (which lacks sigtimedwait) boost.process v1 implements the - // timed waits with a sigwait()-based fallback that deadlocks inside a - // multi-threaded process: SIGCHLD is delivered to an arbitrary thread - // and consumed by an async handler, so the worker thread's sigwait() - // never returns and the timeout never fires — the plugin load hangs - // forever (the "Loading" status never clears). child.running() uses - // waitpid(WNOHANG), which behaves correctly on every platform. - // (boost.process v2, in Boost >= 1.86, implements timed waits via Asio - // and is unaffected — revisit this when the bundled Boost is upgraded.) - constexpr auto kInstallTimeout = std::chrono::seconds(120); - const auto deadline = std::chrono::steady_clock::now() + kInstallTimeout; - - std::error_code run_ec; - while (child.running(run_ec)) { - if (run_ec) { - stderr_reader.join(); - error = "Failed to query uv process status: " + run_ec.message(); - BOOST_LOG_TRIVIAL(error) << error; - return false; - } - if (std::chrono::steady_clock::now() >= deadline) { - std::error_code term_ec; - child.terminate(term_ec); - child.wait(term_ec); - stderr_reader.join(); - error = "uv pip install timed out after 120s"; - BOOST_LOG_TRIVIAL(error) << error; - return false; - } - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - stderr_reader.join(); - - const int exit_code = child.exit_code(); - if (exit_code != 0) { - if (!err_output.empty()) - error = "uv pip install failed (exit code " + std::to_string(exit_code) + "): " + err_output; - else - error = "uv pip install failed with exit code " + std::to_string(exit_code); - BOOST_LOG_TRIVIAL(error) << error; - return false; - } - - BOOST_LOG_TRIVIAL(info) << "Python packages installed successfully"; - return true; - } catch (const std::exception& ex) { - error = std::string("Failed to run uv: ") + ex.what(); - BOOST_LOG_TRIVIAL(error) << error; - return false; - } + return PythonInterpreter::run_uv(args, std::chrono::seconds(120), error); } bool inspect_local_plugin_package(const boost::filesystem::path& filepath, @@ -634,7 +601,11 @@ bool inspect_local_plugin_package(const boost::filesystem::path& filepath, boost::system::error_code ec; const fs::path source_path = canonical_or_absolute(filepath); - if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec)) + // Both the package file chosen by the user and the install folder derived from its name can + // pass the legacy Windows MAX_PATH, where the plain spelling cannot be probed. The descriptor + // keeps the plain paths; only these probes use the extended-length form. + const fs::path io_source_path = extended_path(source_path); + if (!fs::exists(io_source_path, ec) || !fs::is_regular_file(io_source_path, ec)) return fail("Plugin package is not a file: " + filepath.string()); std::string metadata_error; @@ -646,7 +617,7 @@ bool inspect_local_plugin_package(const boost::filesystem::path& filepath, plugin_descriptor.plugin_root = final_dir.string(); ec.clear(); - const fs::file_status final_status = fs::status(final_dir, ec); + const fs::file_status final_status = fs::status(extended_path(final_dir), ec); if (ec && final_status.type() != fs::file_not_found) return fail("Failed to check existing plugin " + final_dir.string() + ": " + ec.message()); @@ -677,6 +648,7 @@ bool install_plugin(const boost::filesystem::path& filepath, const bool is_cloud_install = !cloud_uuid.empty(); fs::path backup_dir; + fs::path io_backup_dir; bool backup_created = false; auto fail = [&error](const std::string& message) { @@ -687,7 +659,14 @@ bool install_plugin(const boost::filesystem::path& filepath, boost::system::error_code ec; const fs::path source_path = canonical_or_absolute(filepath); - if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec)) + // The installed copy is //, so a long + // wheel filename pushes the cache past the legacy Windows MAX_PATH even when the plugin root + // stays well below it. The descriptor and the error messages keep the plain spelling; every + // filesystem operation below goes through the extended-length form, which the Win32 APIs + // accept past the limit. extended_path() is the identity off Windows. + const fs::path io_source_path = extended_path(source_path); + + if (!fs::exists(io_source_path, ec) || !fs::is_regular_file(io_source_path, ec)) return fail(GUI::format(_u8L("Plugin package is not a file: %1%"), filepath.string())); const std::string ext = plugin_package_extension(source_path); @@ -701,7 +680,7 @@ bool install_plugin(const boost::filesystem::path& filepath, const fs::path plugin_root = is_cloud_install && !cloud_user_id.empty() ? fs::path(get_cloud_plugin_dir(cloud_user_id)) : local_plugin_root(); - fs::create_directories(plugin_root, ec); + fs::create_directories(extended_path(plugin_root), ec); if (ec) // TRN %1% is a folder path, %2% the system error message. return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), plugin_root.string(), ec.message())); @@ -735,6 +714,11 @@ bool install_plugin(const boost::filesystem::path& filepath, const fs::path final_dir = is_cloud_install ? plugin_root / cloud_uuid : local_plugin_install_dir(source_path); const fs::path dest_file = final_dir / source_path.filename(); + // The spelled-out install and backup paths above are the identity used by the descriptor and + // the error messages; these are the same locations in the form the filesystem calls need. + const fs::path io_final_dir = extended_path(final_dir); + const fs::path io_dest_file = extended_path(dest_file); + // Local key is the plugin file stem; cloud key is the cloud UUID. if (is_cloud_install) plugin_descriptor.plugin_key = cloud_uuid; @@ -747,12 +731,12 @@ bool install_plugin(const boost::filesystem::path& filepath, auto restore_backup = [&]() { // A fresh install has no backup, but its partial destination must still be removed. boost::system::error_code restore_ec; - fs::remove_all(final_dir, restore_ec); + fs::remove_all(io_final_dir, restore_ec); if (!backup_created) return; restore_ec.clear(); - fs::rename(backup_dir, final_dir, restore_ec); + fs::rename(io_backup_dir, io_final_dir, restore_ec); if (restore_ec) { BOOST_LOG_TRIVIAL(error) << "Failed to restore plugin backup " << backup_dir.string() << " to " << final_dir.string() << ": " << restore_ec.message(); @@ -765,10 +749,11 @@ bool install_plugin(const boost::filesystem::path& filepath, // Backup existing installation if present. The "__" prefix keeps an abandoned backup out of // discovery if the process dies or the final cleanup below cannot remove it. - if (fs::exists(final_dir, ec)) { + if (fs::exists(io_final_dir, ec)) { backup_dir = plugin_root / ("__" + final_dir.filename().string() + ".backup-" + fs::unique_path("%%%%-%%%%-%%%%").string()); - fs::rename(final_dir, backup_dir, ec); + io_backup_dir = extended_path(backup_dir); + fs::rename(io_final_dir, io_backup_dir, ec); if (ec) // TRN %1% is a folder path, %2% the system error message. return fail(GUI::format(_u8L("Failed to back up existing plugin %1%: %2%"), final_dir.string(), ec.message())); @@ -776,13 +761,13 @@ bool install_plugin(const boost::filesystem::path& filepath, } // Create the plugin directory and copy the file. - fs::create_directories(final_dir, ec); + fs::create_directories(io_final_dir, ec); if (ec) { restore_backup(); return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), final_dir.string(), ec.message())); } - fs::copy_file(source_path, dest_file, ec); + fs::copy_file(io_source_path, io_dest_file, ec); if (ec) { restore_backup(); // TRN %1% is a file path, %2% the system error message. @@ -824,7 +809,7 @@ bool install_plugin(const boost::filesystem::path& filepath, if (backup_created) { boost::system::error_code remove_ec; - fs::remove_all(backup_dir, remove_ec); + fs::remove_all(io_backup_dir, remove_ec); if (remove_ec) BOOST_LOG_TRIVIAL(warning) << "Failed to remove plugin backup " << backup_dir.string() << ": " << remove_ec.message(); } @@ -833,7 +818,7 @@ bool install_plugin(const boost::filesystem::path& filepath, if (is_cloud_install) { boost::system::error_code remove_ec; - fs::remove(source_path, remove_ec); + fs::remove(io_source_path, remove_ec); } return true; } diff --git a/src/slic3r/plugin/PythonInterpreter.cpp b/src/slic3r/plugin/PythonInterpreter.cpp index dbec595add..7060d4bf3a 100644 --- a/src/slic3r/plugin/PythonInterpreter.cpp +++ b/src/slic3r/plugin/PythonInterpreter.cpp @@ -6,13 +6,14 @@ #include #include #include +#include #include #include +#include #include #include #include #include -#include "PluginFsUtils.hpp" #include #include @@ -22,12 +23,15 @@ #include #include #include +#include #include #include #include #include #include #include +#include +#include #include #include #include @@ -190,6 +194,91 @@ std::string executable_name(const char* base) #endif } +// The plain Win32 APIs refuse paths at MAX_PATH (260) unless long paths are enabled; +// extended_path() is what reaches past it. Off Windows there is no such limit. +bool fits_plain_windows_path(const boost::filesystem::path& path) +{ +#ifdef _WIN32 + constexpr std::size_t kLegacyWindowsPathLimit = 260; + return path.wstring().size() < kLegacyWindowsPathLimit; +#else + (void) path; + return true; +#endif +} + +// True when `directory` can be listed through its plain spelling and every entry file the finder +// would probe for `stem` also fits there: ".py" or a compiled "..pyd"/".so". +// A namespace package has none of them, so being able to list the directory is all its import +// needs. +bool plain_path_reaches_entry_files(const boost::filesystem::path& directory, const std::string& stem) +{ + namespace fs = boost::filesystem; + + const std::string leaf = stem + "."; + boost::system::error_code ec; + fs::directory_iterator it(directory, ec); + const fs::directory_iterator end; + for (; !ec && it != end; it.increment(ec)) { + const fs::path& candidate = it->path(); + const std::string filename = candidate.filename().string(); + if (filename.compare(0, leaf.size(), leaf) != 0) + continue; + + const std::string ext = candidate.extension().string(); + if (ext != ".py" && ext != ".pyd" && ext != ".so" && ext != ".dll") + continue; + if (!fits_plain_windows_path(candidate)) + return false; + } + + // An unreadable directory cannot be probed; the extended-length form may still reach it. + return !ec; +} + +// True when the plain spelling of the sys.path entry `dir` reaches everything the import of +// `pkg_name` needs. A directory below the legacy Windows MAX_PATH can still hold package files +// above it, and the finder then silently treats the package as a namespace package: an +// unreachable __init__.py reads exactly like a missing one. The probes here therefore check the +// entry files themselves, so a namespace package and a compiled-only package keep the plain +// spelling, while any entry file past the limit gets the extended-length form, which imports it +// just as well. +bool module_entry_reachable(const boost::filesystem::path& dir, const std::string& pkg_name) +{ + namespace fs = boost::filesystem; + + fs::path relative; + std::string component; + for (const char ch : pkg_name) { + if (ch == '.') { + relative /= component; + component.clear(); + } else { + component += ch; + } + } + if (component.empty()) + return false; + relative /= component; + + const fs::path entry = dir / relative; + + boost::system::error_code ec; + if (fs::is_directory(entry, ec)) + return plain_path_reaches_entry_files(entry, "__init__"); + + // Boost reports a missing path through ec too (ENOENT, or on Windows ERROR_FILE_NOT_FOUND / + // ERROR_PATH_NOT_FOUND), so the code alone cannot tell the single-module layout from a path + // past MAX_PATH. The length can: a fitting absent entry is a module that lives next to it, + // while one that does not fit cannot be probed plainly and takes the extended-length form. + if (!fits_plain_windows_path(entry)) + return false; + + // A single module: .py or a compiled ..pyd/.so next to the package path. + const fs::path parent = relative.parent_path().empty() ? dir : dir / relative.parent_path(); + return plain_path_reaches_entry_files(parent, relative.filename().string()); +} + bool add_sys_path_entry(const boost::filesystem::path& path, std::string& error, bool* inserted = nullptr) { if (inserted) @@ -480,6 +569,105 @@ std::string PythonInterpreter::bundled_uv_path() return {}; } +bool PythonInterpreter::run_uv(const std::vector& args, std::chrono::seconds timeout, std::string& error) +{ + error.clear(); + + const std::string uv_path = bundled_uv_path(); + if (uv_path.empty()) { + error = "Bundled uv executable not found. Python package installation is unavailable."; + return false; + } + + try { + namespace process = boost::process; + + process::ipstream std_err; +#ifdef _WIN32 + // boost::process' narrow overload spawns through CreateProcessA, which interprets the + // executable and arguments in the active ANSI codepage. The uv path and every argument + // here are UTF-8 (boost::nowide::nowide_filesystem makes path::string() UTF-8), so hand + // Boost UTF-16 strings and let it spawn through CreateProcessW instead. + const std::wstring uv_path_wide = boost::nowide::widen(uv_path); + std::vector args_wide; + args_wide.reserve(args.size()); + for (const std::string& arg : args) + args_wide.emplace_back(boost::nowide::widen(arg)); +#endif + process::child child( +#ifdef _WIN32 + uv_path_wide, process::args(args_wide), +#else + uv_path, process::args(args), +#endif +#ifdef _WIN32 + // uv.exe (and the python.exe it spawns) are console-subsystem programs. + // OrcaSlicer is a GUI app with no console of its own, so without this flag + // Windows allocates a fresh console window for the child that flashes on + // screen during startup plugin loading. Matches ProcessRunner/MediaPlayCtrl. + process::windows::create_no_window, +#endif + process::std_err > std_err); + + std::string err_output; + std::thread stderr_reader([&std_err, &err_output]() { + std::string line; + while (std::getline(std_err, line)) { + err_output += line + '\n'; + } + }); + + // NOTE: we poll child.running() instead of calling child.wait_for(). + // On macOS (which lacks sigtimedwait) boost.process v1 implements the + // timed waits with a sigwait()-based fallback that deadlocks inside a + // multi-threaded process: SIGCHLD is delivered to an arbitrary thread + // and consumed by an async handler, so the worker thread's sigwait() + // never returns and the timeout never fires — the plugin load hangs + // forever (the "Loading" status never clears). child.running() uses + // waitpid(WNOHANG), which behaves correctly on every platform. + // (boost.process v2, in Boost >= 1.86, implements timed waits via Asio + // and is unaffected — revisit this when the bundled Boost is upgraded.) + const auto deadline = std::chrono::steady_clock::now() + timeout; + + std::error_code run_ec; + while (child.running(run_ec)) { + if (run_ec) { + stderr_reader.join(); + error = "Failed to query uv process status: " + run_ec.message(); + BOOST_LOG_TRIVIAL(error) << error; + return false; + } + if (std::chrono::steady_clock::now() >= deadline) { + std::error_code term_ec; + child.terminate(term_ec); + child.wait(term_ec); + stderr_reader.join(); + error = "uv pip install timed out after " + std::to_string(timeout.count()) + "s"; + BOOST_LOG_TRIVIAL(error) << error; + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + stderr_reader.join(); + + const int exit_code = child.exit_code(); + if (exit_code != 0) { + if (!err_output.empty()) + error = "uv pip install failed (exit code " + std::to_string(exit_code) + "): " + err_output; + else + error = "uv pip install failed with exit code " + std::to_string(exit_code); + BOOST_LOG_TRIVIAL(error) << error; + return false; + } + + return true; + } catch (const std::exception& ex) { + error = std::string("Failed to run uv: ") + ex.what(); + BOOST_LOG_TRIVIAL(error) << error; + return false; + } +} + bool PythonInterpreter::initialize() { std::unique_lock runtime_lock(m_runtime_mutex); @@ -1170,9 +1358,19 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p } namespace fs = boost::filesystem; - fs::path dir(dir_path); + // A wheel cache below the data directory can pass the legacy Windows MAX_PATH, in the + // directory itself or in the package files below it, where boost::filesystem and the + // interpreter's finder cannot reach either. The plain spelling is what the plugin then sees as + // __file__ and sys.path, and what the host compares against the plain plugin root, so it is + // kept while the entry module is reachable through it; otherwise the extended-length form is + // used for the probe and for sys.path, and the recorded entry matches what is on it. + // extended_path() is the identity off Windows. + fs::path io_dir(dir_path); + if (!io_dir.empty() && !module_entry_reachable(io_dir, pkg_name)) + io_dir = extended_path(io_dir); - if (!fs::exists(dir) || !fs::is_directory(dir)) { + boost::system::error_code ec; + if (!fs::is_directory(io_dir, ec) || ec) { error = "Directory does not exist: " + dir_path; return nullptr; } @@ -1183,7 +1381,7 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p return nullptr; } - const std::string directory = dir.string(); + const std::string directory = io_dir.string(); if (!add_plugin_sys_path_locked(directory, error)) return nullptr; if (plugin_paths) @@ -1206,34 +1404,4 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p return module; } -PyObject* PythonInterpreter::load_module_from_whl(const std::string& file_path, - const std::string& pkg_name, - std::string& error, - std::vector* plugin_paths, - std::vector* plugin_modules) -{ - if (!m_initialized.load(std::memory_order_acquire)) { - error = "Python interpreter not initialized"; - return nullptr; - } - - namespace fs = boost::filesystem; - - fs::path whl_path(file_path); - - if (!fs::exists(whl_path)) { - error = "File does not exist: " + file_path; - return nullptr; - } - - fs::path extract_dir = whl_path.parent_path() / "__whl_extracted__" / pkg_name; - - if (!fs::exists(extract_dir)) { - if (!extract_zip_to_directory(whl_path, extract_dir, error)) - return nullptr; - } - - return load_module_from_directory(extract_dir.string(), pkg_name, error, plugin_paths, plugin_modules); -} - } // namespace Slic3r diff --git a/src/slic3r/plugin/PythonInterpreter.hpp b/src/slic3r/plugin/PythonInterpreter.hpp index 1ae9db92be..da71741e77 100644 --- a/src/slic3r/plugin/PythonInterpreter.hpp +++ b/src/slic3r/plugin/PythonInterpreter.hpp @@ -62,6 +62,14 @@ public: // Bundled uv executable path, or empty when uv is not bundled/found. static std::string bundled_uv_path(); + // Run the bundled uv with `args` (everything after the executable), capturing its stderr. + // Blocks the calling thread until the child exits or `timeout` elapses. + // + // `error` is set to an actionable message on failure: a missing bundled uv, a failed wait, a + // timeout, a non-zero exit status, or the exception thrown while spawning the child. Arguments + // are passed as an array; nothing is routed through a shell. + static bool run_uv(const std::vector& args, std::chrono::seconds timeout, std::string& error); + // Python ABI tag for the bundled interpreter, e.g. "cp312". static std::string python_abi_tag(); @@ -86,11 +94,6 @@ public: std::string& error, std::vector* plugin_paths = nullptr, std::vector* plugin_modules = nullptr); - PyObject* load_module_from_whl(const std::string& whl_path, - const std::string& pkg_name, - std::string& error, - std::vector* plugin_paths = nullptr, - std::vector* plugin_modules = nullptr); PyObject* load_module_from_directory(const std::string& dir_path, const std::string& pkg_name, std::string& error, diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index d6f180ac56..3b3e8fb4a9 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -46,6 +46,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_install.cpp test_plugin_update.cpp test_plugin_lifecycle.cpp + test_plugin_wheel_install.cpp test_plugin_resource_texture.cpp test_plugin_printer_agent.cpp test_post_processor.cpp diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index a295230db3..c130b08748 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -5090,6 +5090,76 @@ TEST_CASE("An implicit writable root matches a target spelled with the other 8.3 #endif } +TEST_CASE("An extended-length spelling names the same location as its plain form", "[audit][Regression]") +{ +#ifndef _WIN32 + SKIP("The extended-length path prefix exists only on Windows"); +#else + ScopedTemporaryDir temp{"orca-plugin-audit-extended-paths"}; + const fs::path root = temp.path() / "root"; + const fs::path outside = temp.path() / "outside"; + fs::create_directories(root / "sub"); + fs::create_directories(outside); + + // A plugin's __file__ is spelled the way its sys.path entry was, and a cache past MAX_PATH can + // only be canonicalized in the extended-length form, while allowed roots are registered plainly. + // The same location has to compare equal in both spellings, and the boundary has to stay put. + const fs::path extended_root = extended_path(root); + const fs::path extended_outside = extended_path(outside); + REQUIRE(extended_root != root); + REQUIRE(extended_outside != outside); + + PluginAuditManager& mgr = PluginAuditManager::instance(); + + SECTION("a plain root contains extended-spelled targets") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(root); + + CHECK(is_inside_allowed_root(extended_path(root / "sub" / "file.txt"), root)); + CHECK(is_inside_allowed_root(root, extended_root)); + CHECK(mgr.delete_target_inside_writable_allowed_root(extended_path(root / "sub").string())); + // A target that does not exist yet is still inside: only the existing prefix is compared. + CHECK(mgr.delete_target_inside_writable_allowed_root(extended_path(root / "not-created-yet").string())); + + // Outside stays outside in the extended spelling too, including a name that only shares the + // root's prefix. + CHECK_FALSE(is_inside_allowed_root(extended_outside / "file.txt", root)); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root(extended_outside.string())); + CHECK_FALSE(is_inside_allowed_root(extended_path(fs::path(root.string() + "_sibling") / "file.txt"), root)); + } + + SECTION("an extended-spelled root contains plain targets") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(extended_root); + + CHECK(is_inside_allowed_root(root / "sub" / "file.txt", extended_root)); + CHECK(is_inside_allowed_root(extended_root, root)); + CHECK(mgr.delete_target_inside_writable_allowed_root((root / "sub").string())); + + CHECK_FALSE(is_inside_allowed_root(outside / "file.txt", extended_root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(root.string() + "_sibling"), extended_root)); + } + + SECTION("device paths that are not drive-letter aliases stay outside") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(root); + + // "\\?\C:\..." is the only device-namespace alias of a lettered path that the comparison + // rewrites. A volume GUID, a named pipe, the "\\.\" device namespace and the NT "\??\" + // prefix name other objects, so stripping the prefix would invent a path inside the root; + // they must stay unmatched, as must an extended UNC spelling of some other share. + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\?\\Volume{00000000-0000-0000-0000-000000000000}\\file.txt"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\?\\PIPE\\orca-audit"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\.\\pipe\\orca-audit"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\??\\C:\\Windows\\win.ini"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\?\\UNC\\orca-audit-host\\share\\file.txt"), root)); + } +#endif +} + TEST_CASE("An asynchronous recursive delete approval is single-use and bound to its plugin and target", "[audit][Python]") { AuditHarness harness; diff --git a/tests/slic3rutils/test_plugin_install.cpp b/tests/slic3rutils/test_plugin_install.cpp index 9fb39f277f..1590b5bb96 100644 --- a/tests/slic3rutils/test_plugin_install.cpp +++ b/tests/slic3rutils/test_plugin_install.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -21,6 +22,8 @@ #include "test_utils.hpp" #include +#include +#include #include #include @@ -76,6 +79,43 @@ fs::path to_extended_path(const fs::path& p) return Slic3r::extended_path(p); } +// Write a small sentinel file through the extended-length form too, so a file whose parent sits +// near MAX_PATH can be created and left in place on Windows. +bool write_file_at_extended_path(const fs::path& path, const std::string& contents) +{ + fs::create_directories(to_extended_path(path.parent_path())); +#ifdef _WIN32 + const std::string io_path = boost::nowide::narrow(to_extended_path(path).wstring()); +#else + const std::string io_path = to_extended_path(path).string(); +#endif + boost::nowide::ofstream out(io_path, std::ios::binary | std::ios::trunc); + if (!out) + return false; + out.write(contents.data(), static_cast(contents.size())); + out.close(); + return static_cast(out); +} + +// A minimal installable wheel: one dist-info directory holding METADATA, WHEEL and RECORD, plus a +// module. install_plugin only caches the archive, so the module body is never imported. +void write_wheel(const fs::path& path, const std::string& dist_name) +{ + fs::create_directories(path.parent_path()); + + Zipper zipper(path.string(), Zipper::NO_COMPRESSION); + const std::string module = "VALUE = 1\n"; + const std::string metadata = "Metadata-Version: 2.1\nName: " + dist_name + "\nVersion: 1.0\n\n"; + const std::string wheel = "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n"; + const std::string record = "demo_pkg/__init__.py,,\n"; + const std::string info = dist_name + "-1.0.dist-info/"; + zipper.add_entry("demo_pkg/__init__.py", module.data(), module.size()); + zipper.add_entry(info + "METADATA", metadata.data(), metadata.size()); + zipper.add_entry(info + "WHEEL", wheel.data(), wheel.size()); + zipper.add_entry(info + "RECORD", record.data(), record.size()); + zipper.finalize(); +} + // Brings the plugin system up for a case that drives a real plugin load, and tears it down // afterwards. Declare it first in the test so it is destroyed last; the interpreter itself is // process-wide and finalized once by the suite's run-end handler. @@ -195,6 +235,44 @@ TEST_CASE("install_plugin accepts a side-loaded .py with complete PEP 723 metada CHECK(error.empty()); } +TEST_CASE("install_plugin caches a wheel whose destination passes MAX_PATH", "[PluginInstall][Regression]") +{ + ScopedDataDir data_dir_guard("long-path-install"); + ScopedTemporaryDir wheel_source("long-path-wheel-source"); + + // data_dir()/orca_plugins// is the cached copy. A long distribution + // name in the wheel filename pushes that copy past MAX_PATH while the plugin root stays well + // below it, and the Win32 APIs then refuse to create, copy or read the cache unless every + // operation goes through the extended-length form. + fs::path deep_data_dir = data_dir_guard.dir; + while (deep_data_dir.string().size() < 140) + deep_data_dir /= "deep_component"; + fs::create_directories(to_extended_path(deep_data_dir)); + set_data_dir(deep_data_dir.string()); + + const std::string dist_name = "demo_plugin_with_a_distribution_name_long_enough_to_push_the_cached_copy_past_max_path"; + const fs::path wheel = wheel_source.path() / (dist_name + "-1.0-py3-none-any.whl"); + write_wheel(wheel, dist_name); + if (wheel.string().size() >= 260) + SKIP("Temporary directory is too long for a below-MAX_PATH wheel source"); + + PluginDescriptor descriptor; + std::string error; + REQUIRE(plugin_loader::install_plugin(wheel, /*cloud_user_id=*/"", descriptor, error)); + CHECK(error.empty()); + + // The installed package, its descriptor identity and the sidecar beside it are all below the + // deep plugin folder, so each of them has to be reachable past the limit. + const fs::path installed = fs::path(descriptor.entry_path); + REQUIRE(installed.string().size() > 260); + CHECK(fs::is_regular_file(to_extended_path(installed))); + CHECK(fs::is_regular_file(to_extended_path(fs::path(descriptor.plugin_root) / INSTALL_STATE_FILE))); + + // ScopedDataDir's plain remove_all cannot reach past MAX_PATH on Windows. + boost::system::error_code cleanup_ec; + fs::remove_all(to_extended_path(deep_data_dir), cleanup_ec); +} + TEST_CASE("a .py plugin's PEP 723 dependencies split only at the commas between items", "[PluginInstall][PluginFsUtils]") { // Each layout holds the same two items; the first has a comma inside its quotes, as a version @@ -900,3 +978,99 @@ TEST_CASE("extract_zip_to_directory rejects an entry that escapes the destinatio CHECK_THAT(error, Catch::Matchers::ContainsSubstring("escapes the plugin package")); CHECK_FALSE(fs::exists(dir.path() / "escape.txt")); } + +TEST_CASE("deleting a plugin's install cache reaches a cache root past MAX_PATH", + "[PluginInstall][PluginFsUtils][Regression]") +{ + ScopedTemporaryDir plugins_dir("deep-cache-delete"); + const fs::path plugins_root = plugins_dir.path(); + + // Keep the plugin root below MAX_PATH and size the last component so the cache root, one + // directory deeper, passes it. The removal root is what the extended-length form has to reach. + const std::size_t base_length = plugins_root.string().size(); + if (base_length + 2 > 249) + SKIP("Temporary path is too long for a cache root below MAX_PATH"); + const fs::path plugin_root = plugins_root / std::string(249 - base_length, 'c'); + const fs::path cache_root = plugin_root / plugin_wheel_install::EXTRACTED_DIR_NAME; + REQUIRE(plugin_root.string().size() < 260); + REQUIRE(cache_root.string().size() > 260); + + fs::create_directories(to_extended_path(cache_root / "demo_pkg")); + + // The real layout: the plugin root is a child of orca_plugins, and plugin_data is its sibling + // there, not a child of the plugin root. + const fs::path stored_wheel = plugin_root / "demo_pkg-1.0-py3-none-any.whl"; + const fs::path install_sidecar = plugin_root / INSTALL_STATE_FILE; + const fs::path plugin_data = plugins_root / PLUGIN_DATA_DIR / "demo_plugin"; + const fs::path plugin_data_file = plugin_data / "settings.json"; + REQUIRE(write_file_at_extended_path(stored_wheel, "stored wheel sentinel\n")); + REQUIRE(write_file_at_extended_path(install_sidecar, "{\"enabled\": true}\n")); + REQUIRE(write_file_at_extended_path(plugin_data_file, "{\"value\": 1}\n")); + + std::string error; + const bool removed = plugin_wheel_install::delete_install_cache(plugin_root, error); + INFO("cache delete error: " << error); + REQUIRE(removed); + CHECK(error.empty()); + CHECK_FALSE(fs::exists(to_extended_path(cache_root))); + + // Only the cache goes: the stored wheel, install sidecar, plugin root and the sibling plugin + // data all stay. + CHECK(fs::is_directory(to_extended_path(plugin_root))); + CHECK(fs::is_regular_file(to_extended_path(stored_wheel))); + CHECK(fs::is_regular_file(to_extended_path(install_sidecar))); + CHECK(fs::is_regular_file(to_extended_path(plugin_data_file))); + + // Remove the deep plugin root explicitly; ScopedTemporaryDir cleans up the rest. + boost::system::error_code cleanup_ec; + fs::remove_all(to_extended_path(plugin_root), cleanup_ec); + CHECK_FALSE(cleanup_ec); +} + +TEST_CASE("a deep plugin root is authorized inside its directory and then deleted", + "[PluginInstall][PluginFsUtils][Regression]") +{ + ScopedTemporaryDir dir("deep-plugin-root-delete"); + + const fs::path plugin_root = dir.path() / std::string(240, 'p'); + REQUIRE(plugin_root.string().size() > 260); + fs::create_directories(to_extended_path(plugin_root / "demo_pkg")); + + PluginDescriptor descriptor; + descriptor.plugin_root = plugin_root.string(); + + // The authorization check runs on the same deep root that removal will use. + fs::path resolved_root; + std::string error; + REQUIRE(resolve_allowed_plugin_root(descriptor, {dir.path().string()}, "outside plugin root", + resolved_root, error)); + CHECK(error.empty()); + + const bool deleted = delete_plugin_root(resolved_root, descriptor.plugin_root, error); + INFO("plugin delete error: " << error); + REQUIRE(deleted); + CHECK(error.empty()); + CHECK_FALSE(fs::exists(to_extended_path(plugin_root))); +} + +TEST_CASE("a plugin root outside the allowed directories is rejected before deletion", + "[PluginInstall][PluginFsUtils]") +{ + ScopedTemporaryDir allowed_dir("allowed-plugin-root"); + ScopedTemporaryDir outside_dir("outside-plugin-root"); + + const fs::path outside_root = outside_dir.path() / "plugin"; + fs::create_directories(outside_root); + + PluginDescriptor descriptor; + descriptor.plugin_root = outside_root.string(); + + fs::path resolved_root; + std::string error; + CHECK_FALSE(resolve_allowed_plugin_root(descriptor, {allowed_dir.path().string()}, "outside plugin root", + resolved_root, error)); + CHECK(error == "outside plugin root"); + + // Rejection happens before removal, so the outside root is untouched. + CHECK(fs::is_directory(outside_root)); +} diff --git a/tests/slic3rutils/test_plugin_lifecycle.cpp b/tests/slic3rutils/test_plugin_lifecycle.cpp index 86636f21a5..ed55ef0464 100644 --- a/tests/slic3rutils/test_plugin_lifecycle.cpp +++ b/tests/slic3rutils/test_plugin_lifecycle.cpp @@ -1,9 +1,12 @@ #include #include +#include +#include #include #include #include +#include #include #include #include @@ -27,6 +30,7 @@ #include #include #include +#include #include #include #include "slic3r/plugin/PythonPluginInterface.hpp" @@ -217,6 +221,84 @@ fs::path write_plugin(const ScopedDataDir& data_dir_guard, const std::string& st return plugin_dir; } +// Path forms for a tree past the legacy Windows MAX_PATH (260): the extended-length form reaches +// it and is the identity elsewhere, while the UTF-8 spelling is what the interpreter's filesystem +// encoding and boost::nowide expect on Windows. +fs::path long_path(const fs::path& path) +{ + return extended_path(path); +} + +std::string path_utf8(const fs::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(path.wstring()); +#else + return path.string(); +#endif +} + +// Writes /__init__.py, creating the tree through the extended-length form so the +// fixture is buildable past MAX_PATH on Windows. +void write_long_path_package(const fs::path& package_dir) +{ + boost::system::error_code ec; + fs::create_directories(long_path(package_dir), ec); + REQUIRE_FALSE(ec); + + boost::nowide::ofstream init(path_utf8(long_path(package_dir) / "__init__.py")); + init << "VALUE = \"long\"\n"; + REQUIRE(init.good()); +} + +// Loads the package the way the wheel loader does and checks that its body ran, that the recorded +// sys.path entry is exactly the one on sys.path, and that unloading removes it again. +void check_package_import(const fs::path& package_parent, const std::string& pkg_name) +{ + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + // The plain path goes in: reaching the files is the loader's job, not the caller's. + PyObject* module = interpreter.load_module_from_directory(path_utf8(package_parent), pkg_name, error, &paths, &modules); + INFO("module load error: " << error); + REQUIRE(module != nullptr); + REQUIRE(error.empty()); + REQUIRE(paths.size() == 1); + + { + PythonGILState gil; + REQUIRE(gil); + PyObjectPtr value(PyObject_GetAttrString(module, "VALUE")); + REQUIRE(value); + REQUIRE(PyUnicode_Check(value.get())); + CHECK(std::string(PyUnicode_AsUTF8(value.get())) == "long"); + + PyObject* sys_path = PySys_GetObject("path"); + REQUIRE(sys_path != nullptr); + PyObjectPtr entry(PyUnicode_DecodeFSDefault(paths.front().c_str())); + REQUIRE(entry); + CHECK(PySequence_Contains(sys_path, entry.get()) == 1); + } + + Plugin loaded; + loaded.module = module; + loaded.module_name = pkg_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); + + { + PythonGILState gil; + REQUIRE(gil); + PyObject* sys_path = PySys_GetObject("path"); + REQUIRE(sys_path != nullptr); + PyObjectPtr entry(PyUnicode_DecodeFSDefault(paths.front().c_str())); + REQUIRE(entry); + CHECK(PySequence_Contains(sys_path, entry.get()) == 0); + } +} + // Loads a plugin and blocks until the detached worker thread is done with it. bool load_and_wait(PluginManager& manager, const std::string& plugin_key, @@ -738,6 +820,184 @@ TEST_CASE("Python module release removes package submodules and owned sys.path", loaded.release_module(); } +TEST_CASE("A package imports from a plugin directory longer than MAX_PATH", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("long-path-import-dir"); + + // The sys.path entry itself — the wheel cache — is past the legacy Windows MAX_PATH, so it can + // be neither probed nor imported from through the plain spelling. Components stay short enough + // for NAME_MAX on every platform, so the same tree is valid off Windows. + fs::path package_parent = dir.path(); + while (path_utf8(package_parent).size() < 280) + package_parent /= "deep_plugin_directory_component"; + REQUIRE(path_utf8(package_parent).size() > 260); + + write_long_path_package(package_parent / "long_path_package"); + check_package_import(package_parent, "long_path_package"); + + // Only the extended-length form can remove the deep tree on Windows; the guard then removes + // the shallow remainder. + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(package_parent), cleanup_ec); +} + +TEST_CASE("A package imports when only its files pass MAX_PATH", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("long-path-import-files"); + + // The sys.path entry stays below the limit, so a directory probe alone would accept it, but the + // package file below it does not. The finder reads the unreachable __init__.py as absent and + // accepts the directory as a namespace package, so the loader has to check the entry file + // instead of the directory. + fs::path package_parent = dir.path(); + const std::size_t base_len = path_utf8(package_parent).size() + 1; // the separator before padding + const std::size_t target_len = 250; + if (base_len >= target_len) + SKIP("Temporary directory is too long for a below-MAX_PATH parent"); + package_parent /= std::string(target_len - base_len, 'd'); + REQUIRE(path_utf8(package_parent).size() == target_len); + + const fs::path package_dir = package_parent / "long_path_package"; + REQUIRE(path_utf8(package_dir / "__init__.py").size() > 260); + + write_long_path_package(package_dir); + check_package_import(package_parent, "long_path_package"); + + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(package_parent), cleanup_ec); +} + +TEST_CASE("A namespace package imports through its plain directory path", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("plain-import-namespace"); + const fs::path package_parent = dir.path(); + const std::string pkg_name = "orca_test_namespace_package"; + fs::create_directories(package_parent / pkg_name); + { + std::ofstream submodule((package_parent / pkg_name / "submodule.py").string(), std::ios::binary); + submodule << "VALUE = \"namespace\"\n"; + REQUIRE(submodule.good()); + } + + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + PyObject* module = interpreter.load_module_from_directory(path_utf8(package_parent), pkg_name, error, &paths, &modules); + INFO("module load error: " << error); + REQUIRE(module != nullptr); + REQUIRE(paths.size() == 1); + + // The directory is short enough for the plain Win32 APIs, and a namespace package has no + // __init__.py to probe, so the spelling the caller passed must be the one recorded rather than + // an extended-length path. + CHECK(paths.front() == path_utf8(package_parent)); + + Plugin loaded; + loaded.module = module; + loaded.module_name = pkg_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); +} + +TEST_CASE("A compiled-only package keeps its plain directory path", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("plain-import-compiled"); + const fs::path package_parent = dir.path(); + const std::string pkg_name = "orca_test_compiled_package"; + fs::create_directories(package_parent / pkg_name); + // A package with no .py entry at all: only a compiled initializer the finder probes by name. + // The fixture is not a loadable extension module, so the import itself fails; the recorded + // sys.path entry is what this test protects. A short directory must not gain the extended-length + // prefix just because there is no .py file to probe. +#ifdef _WIN32 + const fs::path compiled_init = package_parent / pkg_name / "__init__.pyd"; +#else + const fs::path compiled_init = package_parent / pkg_name / "__init__.so"; +#endif + { + std::ofstream compiled(compiled_init.string(), std::ios::binary); + compiled << "not a real extension module\n"; + REQUIRE(compiled.good()); + } + + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + PyObject* module = interpreter.load_module_from_directory(path_utf8(package_parent), pkg_name, error, &paths, &modules); + CHECK(module == nullptr); + CHECK_FALSE(error.empty()); + REQUIRE(paths.size() == 1); + CHECK(paths.front() == path_utf8(package_parent)); + + Plugin loaded; + loaded.module = module; + loaded.module_name = pkg_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); +} + +TEST_CASE("A compiled-only module keeps its plain directory path", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("plain-import-compiled-module"); + const fs::path module_parent = dir.path(); + const std::string module_name = "orca_test_compiled_module"; + // A top-level compiled module has no directory beside it, so the probe of that path + // reports "not found". That must not be read as a path past MAX_PATH. As with the package + // fixture, the file is not a loadable extension module, so the import fails after the sys.path + // entry has been recorded. +#ifdef _WIN32 + const fs::path compiled_module = module_parent / (module_name + ".pyd"); +#else + const fs::path compiled_module = module_parent / (module_name + ".so"); +#endif + { + std::ofstream compiled(compiled_module.string(), std::ios::binary); + compiled << "not a real extension module\n"; + REQUIRE(compiled.good()); + } + + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + PyObject* module = interpreter.load_module_from_directory(path_utf8(module_parent), module_name, error, &paths, &modules); + CHECK(module == nullptr); + CHECK_FALSE(error.empty()); + REQUIRE(paths.size() == 1); + CHECK(paths.front() == path_utf8(module_parent)); + + Plugin loaded; + loaded.module = module; + loaded.module_name = module_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); +} + TEST_CASE("A capability disabled in the sidecar loads disabled", "[PluginLifecycle][Python]") { ScopedPluginManager plugin_system; diff --git a/tests/slic3rutils/test_plugin_wheel_install.cpp b/tests/slic3rutils/test_plugin_wheel_install.cpp new file mode 100644 index 0000000000..b6df07d6fb --- /dev/null +++ b/tests/slic3rutils/test_plugin_wheel_install.cpp @@ -0,0 +1,810 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "catch2/catch_test_macros.hpp" +#include "catch2/matchers/catch_matchers.hpp" +#include "test_utils.hpp" + +using namespace Slic3r; +namespace fs = boost::filesystem; +namespace wheel_install = Slic3r::plugin_wheel_install; + +namespace { + +// The long-path-capable form of a path, which the production code and a real uv (Rust std) use on +// Windows past MAX_PATH. A test that reaches a deep cache has to reach it the same way; on other +// platforms both helpers are the identity. +fs::path long_path(const fs::path& path) +{ + return extended_path(path); +} + +std::string long_path_utf8(const fs::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(extended_path(path).wstring()); +#else + return path.string(); +#endif +} + +void write_wheel(const fs::path& path, + const std::string& tag, + const std::string& module_payload, + const std::string& dist_name = "demo_pkg", + const std::string& version = "1.0") +{ + const fs::path io_path = long_path(path); + if (fs::exists(io_path)) + fs::remove(io_path); + + Zipper zipper(path.string(), Zipper::NO_COMPRESSION); + + const std::string metadata = "Metadata-Version: 2.1\nName: demo-pkg\nVersion: " + version + "\n\n"; + zipper.add_entry(dist_name + "/__init__.py", module_payload.data(), module_payload.size()); + zipper.add_entry(dist_name + "-" + version + ".dist-info/METADATA", metadata.data(), metadata.size()); + + const std::string wheel = "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: " + tag + "\n"; + zipper.add_entry(dist_name + "-" + version + ".dist-info/WHEEL", wheel.data(), wheel.size()); + + const std::string record = dist_name + "/__init__.py,,\n"; + zipper.add_entry(dist_name + "-" + version + ".dist-info/RECORD", record.data(), record.size()); + + zipper.finalize(); +} + +PluginDescriptor make_descriptor(const fs::path& plugin_root, const fs::path& wheel) +{ + PluginDescriptor descriptor; + descriptor.plugin_key = "demo_plugin"; + descriptor.plugin_root = plugin_root.string(); + descriptor.entry_path = wheel.string(); + descriptor.entry_package = "demo_pkg"; + descriptor.set_metadata_valid(true); + return descriptor; +} + +std::string arg_after(const std::vector& args, const std::string& flag) +{ + for (std::size_t i = 0; i + 1 < args.size(); ++i) { + if (args[i] == flag) + return args[i + 1]; + } + return {}; +} + +// A uv stand-in: creates the directory tree uv would have installed into. It records the command +// line so a test can assert on the staged filename and the safety flags. +wheel_install::UvRunner fake_uv(std::vector* captured, int* call_count, std::string failure) +{ + return [captured, call_count, failure](const std::vector& args, std::chrono::seconds, std::string& error) { + if (call_count != nullptr) + ++*call_count; + if (captured != nullptr) + *captured = args; + + if (!failure.empty()) { + error = failure; + return false; + } + + const fs::path target = arg_after(args, "--target"); + if (target.empty()) { + error = "fake uv: no --target"; + return false; + } + + // The staged wheel must be a real file with a PEP 427 filename, not the stored name. + const fs::path staged(args.back()); + if (!fs::is_regular_file(long_path(staged))) { + error = "fake uv: staged wheel missing"; + return false; + } + + // A real uv writes the target even when it is past MAX_PATH, so this stand-in must too. + fs::create_directories(long_path(target / "demo_pkg")); + boost::nowide::ofstream init(long_path_utf8(target / "demo_pkg" / "__init__.py")); + init << "VALUE = 1\n"; + return true; + }; +} + +// Neither a staging directory nor a retired-previous directory may outlive a successful install. +bool has_install_scratch_leftovers(const fs::path& plugin_root) +{ + for (fs::directory_iterator it(long_path(plugin_root)); it != fs::directory_iterator(); ++it) { + const std::string name = it->path().filename().string(); + if (name.rfind(wheel_install::STAGING_DIR_PREFIX, 0) == 0 || + name.rfind(wheel_install::PREVIOUS_DIR_PREFIX, 0) == 0) + return true; + } + return false; +} + +// A plugin folder deep enough that its install cache and staging paths exceed the legacy Windows +// MAX_PATH (260), while every component stays far below NAME_MAX so the path is also valid on +// Linux and macOS. +fs::path make_deep_plugin_root(const fs::path& base) +{ + fs::path path = base; + while (path.string().size() < 300) + path /= "deep_plugin_directory_component"; + return path / "plugin"; +} + +// A parent directory that still fits below MAX_PATH (260) while /plugin and a standard +// wheel file name inside it do not: discovery has to enumerate the entry past that limit. +fs::path make_boundary_plugin_parent(const fs::path& base) +{ + constexpr std::size_t parent_length = 230; + const std::string component = "boundary_plugin_directory"; + fs::path path = base; + while (path.string().size() + 1 + component.size() < parent_length) + path /= component; + if (path.string().size() + 1 < parent_length) + path /= std::string(parent_length - path.string().size() - 1, 'p'); + return path; +} + +} // namespace + +TEST_CASE("wheel filenames are validated by their PEP 427 shape", "[PluginWheelInstall]") +{ + CHECK(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none-any.whl")); + CHECK(wheel_install::is_valid_wheel_filename("demo_pkg-1.0-1build-py3-none-any.whl")); + CHECK(wheel_install::is_valid_wheel_filename("demo-1.0+local-cp312-cp312-manylinux_2_17_x86_64.whl")); + CHECK(wheel_install::is_valid_wheel_filename("demo-1!2.0-py3-none-any.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none-any!.whl")); + + // Too few or too many components, a non-.whl extension, an empty component, or a path separator + // is not a wheel filename uv would accept. + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none-any.zip")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0--py3-none-any.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo/1.0-py3-none-any.whl")); + + // A cloud download name splits into five components but its components are not tags, so it + // must be restaged from metadata before uv sees it. + CHECK_FALSE(wheel_install::is_valid_wheel_filename("cloud_plugin-1a2b-3c4d-5e6f-7a8b9c0d1e2f.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-notaversion-py3-none-any.whl")); +} + +TEST_CASE("a missing wheel filename is rebuilt from metadata", "[PluginWheelInstall]") +{ + CHECK(wheel_install::make_wheel_filename("My Plugin", "1.0.0", "py3-none-any") == + "My_Plugin-1.0.0-py3-none-any.whl"); + CHECK(wheel_install::make_wheel_filename("demo", "1!2.0", "py3-none-any") == + "demo-1!2.0-py3-none-any.whl"); + + // The tag is a python-abi-platform triple, so its two '-' separators are part of the tag and + // must survive into the filename, which then has to pass the wheel-filename check. + const std::string pure = wheel_install::make_wheel_filename("demo", "1.0", "py3-none-any"); + REQUIRE_FALSE(pure.empty()); + CHECK(pure == "demo-1.0-py3-none-any.whl"); + CHECK(wheel_install::is_valid_wheel_filename(pure)); + + const std::string native = + wheel_install::make_wheel_filename("demo", "1.0", "cp312-cp312-manylinux_2_17_x86_64"); + REQUIRE_FALSE(native.empty()); + CHECK(native == "demo-1.0-cp312-cp312-manylinux_2_17_x86_64.whl"); + CHECK(wheel_install::is_valid_wheel_filename(native)); + + // Characters uv would reject are escaped; a component that escapes to nothing is refused. + CHECK(wheel_install::make_wheel_filename("demo", "1.0 rc1", "py3-none-any") == "demo-1.0_rc1-py3-none-any.whl"); + CHECK(wheel_install::make_wheel_filename("", "1.0", "py3-none-any").empty()); + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "").empty()); + + // Not a triple, or not a plausible triple: no valid wheel filename can be built. + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "py3-none").empty()); + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "py3/any").empty()); + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "abc-def-ghi").empty()); +} + +TEST_CASE("a staged wheel filename uses the tags the wheel declares", "[PluginWheelInstall]") +{ + CHECK(wheel_install::wheel_filename_tag({}).empty()); + CHECK(wheel_install::wheel_filename_tag({"not-a-tag"}).empty()); + + // No tag is invented: a wheel that only declares py2 keeps that declared tag (uv reports the + // incompatibility), while a wheel declaring both uses the interpreter-compatible one. + CHECK(wheel_install::wheel_filename_tag({"py2-none-any"}) == "py2-none-any"); + CHECK(wheel_install::wheel_filename_tag({"py2-none-any", "py3-none-any"}) == "py3-none-any"); + CHECK(wheel_install::wheel_filename_tag({"cp311-cp311-linux_x86_64", "cp312-cp312-linux_x86_64"}) == + "cp312-cp312-linux_x86_64"); + + // Tags that differ only in platform are combined into a standard compressed tag set. + CHECK(wheel_install::wheel_filename_tag({"cp312-cp312-manylinux_2_17_x86_64", + "cp312-cp312-musllinux_1_2_x86_64"}) == + "cp312-cp312-manylinux_2_17_x86_64.musllinux_1_2_x86_64"); + + // A different interpreter/ABI tag is not merged: the first declared tag is kept. + CHECK(wheel_install::wheel_filename_tag({"cp312-cp312-linux_x86_64", "cp311-cp311-linux_x86_64"}) == + "cp312-cp312-linux_x86_64"); +} + +TEST_CASE("the uv wheel target reuses the legacy entry extraction path", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-target"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + + // One cache location: the directory the pre-uv loader extracted the entry wheel into. + const fs::path expected = plugin_root / "__whl_extracted__" / "demo_pkg"; + CHECK(fs::path(wheel_install::install_dir(plugin_root.string(), "demo_pkg")) == expected); + CHECK(fs::path(wheel_install::install_dir(plugin_root.string(), "pkg.sub")) == + plugin_root / "__whl_extracted__" / "pkg.sub"); + + // The entry package becomes a path component, so path syntax and traversal are refused. + CHECK(wheel_install::install_dir(plugin_root.string(), "").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "../escape").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "pkg/sub").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "pkg\\sub").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), ".hidden").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "pkg..sub").empty()); +} + +TEST_CASE("a markerless legacy extraction is used directly without running uv", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-legacy-accept"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // A pre-uv extraction, plus a separate dependency extraction that must survive. + const fs::path legacy_target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + const fs::path dep_dir = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "dep_pkg"; + fs::create_directories(legacy_target / "demo_pkg"); + fs::create_directories(dep_dir); + { + std::ofstream legacy_file((legacy_target / "written_by_plugin.txt").string()); + legacy_file << "old cache contents\n"; + std::ofstream init_file((legacy_target / "demo_pkg" / "__init__.py").string()); + init_file << "VALUE = 1\n"; + std::ofstream dep_file((dep_dir / "sentinel.txt").string()); + dep_file << "dependency extraction\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + + // The legacy extraction is importable as-is, so it is used without being rewritten. + CHECK(fs::is_regular_file(legacy_target / "written_by_plugin.txt")); + CHECK(fs::is_regular_file(legacy_target / "demo_pkg" / "__init__.py")); + CHECK_FALSE(fs::exists(legacy_target / wheel_install::MARKER_FILE_NAME)); + + // Dependency extractions under the same parent are untouched. + CHECK(fs::is_regular_file(dep_dir / "sentinel.txt")); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a markerless entry target without the entry package is replaced", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-legacy-incomplete"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "incomplete extraction\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + CHECK_FALSE(fs::exists(target / "sentinel.txt")); + CHECK(fs::is_regular_file(target / "demo_pkg" / "__init__.py")); + CHECK(fs::is_regular_file(target / wheel_install::MARKER_FILE_NAME)); +} + +TEST_CASE("an invalid marker still triggers reinstallation", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-invalid-marker"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // A marker makes the target uv-managed even when it is unreadable, so the entry package that + // is present does not turn it into an accepted legacy extraction. + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target / "demo_pkg"); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "stale uv installation\n"; + std::ofstream marker((target / wheel_install::MARKER_FILE_NAME).string()); + marker << "not json\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + CHECK_FALSE(fs::exists(target / "sentinel.txt")); + CHECK(fs::is_regular_file(target / "demo_pkg" / "__init__.py")); +} + +TEST_CASE("the shared extraction parent alone is not a legacy entry extraction", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-parent-only"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // Dependency extractions under __whl_extracted__/ do not make the entry look installed. + const fs::path dep_dir = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "dep_pkg"; + fs::create_directories(dep_dir); + { + std::ofstream dep_file((dep_dir / "__init__.py").string()); + dep_file << "DEPENDENCY = 1\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + CHECK(fs::is_directory(plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg")); + CHECK(fs::is_regular_file(dep_dir / "__init__.py")); +} + +TEST_CASE("a dependency extraction at the entry target is not replaced", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-collision"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + // A dependency wheel whose stem is the entry package maps to the same extraction directory. + write_wheel(plugin_root / "demo_pkg.whl", "py3-none-any", "DEPENDENCY = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "dependency extraction\n"; + } + + int calls = 0; + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("collides")); + + // The dependency extraction is left exactly as it was. + CHECK(fs::is_regular_file(target / "sentinel.txt")); + CHECK_FALSE(fs::exists(target / "demo_pkg")); +} + +TEST_CASE("the entry wheel itself is not treated as a dependency collision", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-entry-stem"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + // A stored wheel renamed to exactly the entry package: its stem matches the target directory, + // but it is the entry and must not be mistaken for a dependency extraction. + const fs::path wheel = plugin_root / "demo_pkg.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + CHECK(fs::is_directory(plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg")); +} + +TEST_CASE("an uppercase dependency wheel extension is treated as a wheel", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-uppercase-dependency"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + // The extension is matched case-insensitively everywhere a wheel is recognized, so this + // dependency maps to the same extraction directory as the entry package and must be refused. + write_wheel(plugin_root / "demo_pkg.WHL", "py3-none-any", "DEPENDENCY = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("collides")); + CHECK_FALSE(fs::exists(plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg")); +} + +TEST_CASE("non-ASCII entry package names are accepted", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-unicode-package"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + + // "pkg_ü" in UTF-8. A Unicode Python identifier must remain a safe path component. + const std::string unicode_package = "pkg_\xC3\xBC"; + CHECK(wheel_install::is_valid_entry_package(unicode_package)); + CHECK(fs::path(wheel_install::install_dir(plugin_root.string(), unicode_package)) == + plugin_root / wheel_install::EXTRACTED_DIR_NAME / unicode_package); +} + +TEST_CASE("an unsafe entry package is rejected before touching the disk", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-unsafe-package"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + for (const std::string& entry_package : + {"../escape", "pkg/sub", "pkg\\sub", "pkg..sub", ".hidden", "pkg*sub", "pkg:sub", "pkg\x01sub"}) { + PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + descriptor.entry_package = entry_package; + + int calls = 0; + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + CHECK_FALSE(fs::exists(plugin_root / wheel_install::EXTRACTED_DIR_NAME)); + } +} + +TEST_CASE("a failed uv install leaves the previous extraction in place", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-legacy-fail"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "previous contents\n"; + } + + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, nullptr, "simulated uv failure"))); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("simulated uv failure")); + + // uv failed before promotion, so the previous directory is still the only cache copy. + CHECK(fs::is_regular_file(target / "sentinel.txt")); + CHECK_FALSE(fs::exists(target / "demo_pkg")); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a wheel with an invalid stored name is staged under a valid name", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-stage"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + int calls = 0; + std::string error; + + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, &calls, ""))); + CHECK(error.empty()); + CHECK(calls == 1); + + // The stored wheel keeps its name; only the staged copy uv reads carries a valid one. + CHECK(fs::path(descriptor.entry_path).filename().string() == "plugin.whl"); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); + // uv installs into a staging target; the promoted target is the one loading uses. + const fs::path uv_target(arg_after(captured, "--target")); + CHECK(uv_target.filename().string() == "target"); + CHECK(uv_target.parent_path().filename().string().rfind(wheel_install::STAGING_DIR_PREFIX, 0) == 0); + const std::string installed_dir = wheel_install::install_dir(plugin_root.string(), "demo_pkg"); + CHECK(uv_target != fs::path(installed_dir)); + CHECK(std::find(captured.begin(), captured.end(), "--no-deps") != captured.end()); + CHECK(std::find(captured.begin(), captured.end(), "--no-index") != captured.end()); + CHECK(std::find(captured.begin(), captured.end(), "--no-python-downloads") != captured.end()); + + CHECK(fs::is_directory(installed_dir)); + CHECK(fs::path(installed_dir) == plugin_root / "__whl_extracted__" / "demo_pkg"); + CHECK(fs::is_regular_file(fs::path(installed_dir) / wheel_install::MARKER_FILE_NAME)); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a wheel with a valid stored name is passed to uv unchanged", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-valid-name"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, nullptr, ""))); + + // The stored wheel is neither renamed on disk nor renamed in the staged copy. + CHECK(fs::path(descriptor.entry_path).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); +} + +TEST_CASE("an uppercase stored wheel extension is staged under a lowercase .whl name", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-uppercase"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.WHL"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, nullptr, ""))); + + // The stored file keeps its name; uv only sees the lowercase extension it accepts. + CHECK(fs::path(descriptor.entry_path).filename().string() == "demo_pkg-1.0-py3-none-any.WHL"); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); +} + +TEST_CASE("an unchanged wheel reuses its installation without running uv again", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-reuse"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + REQUIRE(calls == 1); + + // No uv invocation, no network, no disk rewrite on the next load. + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 1); +} + +TEST_CASE("changed wheel content invalidates the uv installation", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-changed"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + REQUIRE(calls == 1); + + write_wheel(wheel, "py3-none-any", "VALUE = 2\n"); + + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 2); +} + +TEST_CASE("a failed uv install leaves no importable target behind", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-fail"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, nullptr, "simulated uv failure"))); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("simulated uv failure")); + + CHECK_FALSE(fs::exists(wheel_install::install_dir(plugin_root.string(), "demo_pkg"))); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a declared wheel tag is used unchanged in the staged filename", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-declared-tag"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + // A Python-2-only tag: the backend never rewrites it into a claim about this interpreter. uv + // performs the compatibility check on the staged filename. + write_wheel(wheel, "py2-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, &calls, ""))); + CHECK(calls == 1); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py2-none-any.whl"); +} + +TEST_CASE("a wheel installs into a plugin path longer than MAX_PATH", "[PluginWheelInstall][Regression]") +{ + ScopedTemporaryDir dir("wheel-install-long-path"); + const fs::path plugin_root = make_deep_plugin_root(dir.path()); + // Past the legacy Windows MAX_PATH (260): the staging, cache, marker and promotion paths are + // all deeper still, so none of them is reachable without the extended-length form there. The + // same tree is valid on Linux and macOS. + REQUIRE(plugin_root.string().size() > 260); + fs::create_directories(long_path(plugin_root)); + + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // An incomplete previous extraction: the install has to retire and replace it, so the + // promotion renames and the cleanup of the retired directory run on deep paths too. + const fs::path target = long_path(fs::path(wheel_install::install_dir(plugin_root.string(), "demo_pkg"))); + fs::create_directories(target); + { + boost::nowide::ofstream sentinel(long_path_utf8(target / "sentinel.txt")); + sentinel << "previous contents\n"; + } + + std::vector captured; + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, &calls, ""))); + CHECK(error.empty()); + CHECK(calls == 1); + // The wheel's stored name is invalid, so it is staged under a PEP 427 name read from the + // metadata of the deep wheel. + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); + + // The new extraction, its marker and the entry package are all readable at the deep cache + // path, and the retired previous extraction is gone. + CHECK(fs::is_directory(target / "demo_pkg")); + CHECK(fs::is_regular_file(target / "demo_pkg" / "__init__.py")); + CHECK(fs::is_regular_file(target / wheel_install::MARKER_FILE_NAME)); + CHECK_FALSE(fs::exists(target / "sentinel.txt")); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); + + // The marker and the entry wheel fingerprint are read back from the deep paths, so no uv run + // and no rewrite happens on the next load. + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 1); + + // The scoped temp guard removes the base directory best-effort, but a path past MAX_PATH needs + // the extended form to be removed at all. + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(plugin_root), cleanup_ec); +} + +TEST_CASE("an uppercase wheel extension is discovered as a wheel plugin", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-uppercase-discovery"); + const fs::path plugin_parent = dir.path() / "plugins"; + const fs::path plugin_root = plugin_parent / "demo_plugin"; + fs::create_directories(plugin_root); + // A package stored with an upper-case extension is still a wheel: discovery has to read its + // metadata instead of reporting a .py entry that does not exist. + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.WHL"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + std::string error; + const std::vector discovered = discover_plugin_packages({plugin_parent.string()}, error); + REQUIRE(error.empty()); + REQUIRE(discovered.size() == 1); + CHECK(discovered.front().is_metadata_valid()); + CHECK(discovered.front().entry_package == "demo_pkg"); + CHECK(discovered.front().entry_path == wheel.string()); +} + +TEST_CASE("a wheel is discovered under a plugin folder just below MAX_PATH", "[PluginWheelInstall][Regression]") +{ + ScopedTemporaryDir dir("wheel-install-discovery-boundary"); + const fs::path plugin_parent = make_boundary_plugin_parent(dir.path()); + const fs::path plugin_root = plugin_parent / "plugin"; + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.whl"; + // The plugin folder fits below MAX_PATH; the entry wheel inside it does not, so discovery has to + // probe the children in extended form or the package looks like it has no entry file at all. + REQUIRE(plugin_root.string().size() < 260); + REQUIRE(wheel.string().size() > 260); + fs::create_directories(long_path(plugin_root)); + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + std::string error; + const std::vector discovered = discover_plugin_packages({plugin_parent.string()}, error); + REQUIRE(error.empty()); + REQUIRE(discovered.size() == 1); + CHECK(discovered.front().is_metadata_valid()); + CHECK(discovered.front().entry_package == "demo_pkg"); + // The discovered paths keep their normal spelling; only the probes use the extended form. + CHECK(discovered.front().plugin_root == plugin_root.string()); + CHECK(discovered.front().entry_path == wheel.string()); + + // The install stages one level deeper still, and the next load reuses it from the marker. + int calls = 0; + std::string install_error; + REQUIRE(wheel_install::ensure_installed(discovered.front(), install_error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + const fs::path target = long_path(fs::path(wheel_install::install_dir(plugin_root.string(), "demo_pkg"))); + CHECK(fs::is_regular_file(target / wheel_install::MARKER_FILE_NAME)); + REQUIRE(wheel_install::ensure_installed(discovered.front(), install_error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 1); + + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(plugin_root), cleanup_ec); +} + +TEST_CASE("the install-state marker round-trips at a path longer than MAX_PATH", "[PluginWheelInstall][Regression]") +{ + ScopedTemporaryDir dir("plugin-state-long-path"); + const fs::path plugin_root = make_deep_plugin_root(dir.path()); + REQUIRE(plugin_root.string().size() > 260); + fs::create_directories(long_path(plugin_root)); + + PluginDescriptor descriptor = make_descriptor(plugin_root, plugin_root / "plugin.whl"); + descriptor.name = "Demo Plugin"; + + // The sidecar is written through a temporary in the same deep directory and moved into place + // with the platform replace primitive, then read back through the same extended paths. + PluginInstallState state; + { + // The sidecar API expects the install-state lock across its read-modify-write callers. + std::lock_guard state_lock(install_state_mutex()); + REQUIRE(write_install_state(plugin_root, descriptor)); + REQUIRE(read_install_state(plugin_root, state)); + } + CHECK(fs::is_regular_file(long_path(plugin_root / INSTALL_STATE_FILE))); + CHECK(state.plugin_name == "Demo Plugin"); + CHECK(state.installed_from == "local"); + + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(plugin_root), cleanup_ec); +}