diff --git a/src/libslic3r/UpdateChannel.cpp b/src/libslic3r/UpdateChannel.cpp index d5e0db3f92..37bcd3cb73 100644 --- a/src/libslic3r/UpdateChannel.cpp +++ b/src/libslic3r/UpdateChannel.cpp @@ -181,6 +181,43 @@ bool is_newer_version(const std::string& candidate_version, const std::string& r return *candidate > *running; } +// CI uploads nightly assets up to about an hour after the build starts, and the release's +// updated_at follows the last upload, so a release only counts as newer past this margin. +constexpr int64_t kNightlyBuildMargin = 6 * 60 * 60; + +// Seconds since the Unix epoch for a UTC "YYYY-MM-DDTHH:MM:SSZ" stamp. +bool parse_utc_timestamp(const std::string& text, int64_t& seconds) +{ + int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0; + char zone = 0; + if (std::sscanf(text.c_str(), "%d-%d-%dT%d:%d:%d%c", &year, &month, &day, &hour, &minute, &second, &zone) != 7 || + zone != 'Z') + return false; + if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 60) + return false; + + // Days since the epoch from the civil date (proleptic Gregorian calendar). + const int64_t y = year - (month <= 2 ? 1 : 0); + const int64_t era = (y >= 0 ? y : y - 399) / 400; + const int64_t yoe = y - era * 400; + const int64_t doy = (153 * (month > 2 ? month - 3 : month + 9) + 2) / 5 + day - 1; + const int64_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + const int64_t days = era * 146097 + doe - 719468; + + seconds = ((days * 24 + hour) * 60 + minute) * 60 + second; + return true; +} + +// False when either stamp does not parse, so an unknown build is never offered a nightly. +bool nightly_is_newer_than_build(const std::string& release_time, const std::string& build_timestamp) +{ + int64_t release_seconds = 0; + int64_t build_seconds = 0; + if (!parse_utc_timestamp(release_time, release_seconds) || !parse_utc_timestamp(build_timestamp, build_seconds)) + return false; + return release_seconds > build_seconds + kNightlyBuildMargin; +} + } // namespace std::string update_channel_key(UpdateChannel channel) @@ -341,7 +378,7 @@ UpdateCandidate resolve_update(const std::string& releases_json, release_is_newer = is_newer_version(candidate.version, running_version); } else if (!installed_artifact.empty()) { release_is_newer = true; - } else if (!build_timestamp.empty() && candidate.version > build_timestamp) { + } else if (nightly_is_newer_than_build(candidate.version, build_timestamp)) { release_is_newer = true; } @@ -372,7 +409,7 @@ UpdateCandidate resolve_update(const std::string& releases_json, candidate.reason = "source_build"; return candidate; } - if (candidate.version <= build_timestamp) { + if (!nightly_is_newer_than_build(candidate.version, build_timestamp)) { candidate.reason = "up_to_date"; return candidate; } diff --git a/src/libslic3r/UpdateHandoff.cpp b/src/libslic3r/UpdateHandoff.cpp index 597ec56fd9..b900c264ff 100644 --- a/src/libslic3r/UpdateHandoff.cpp +++ b/src/libslic3r/UpdateHandoff.cpp @@ -6,10 +6,13 @@ #include #include #include +#include #include #include #include #include +#include +#include #include #include @@ -26,15 +29,11 @@ #include "Utils.hpp" #ifdef _WIN32 -#include -#include -#include -#include #include #else -#include #include -#include +#include +#include #include #include #endif @@ -133,65 +132,93 @@ void remove_file(const std::string& path) fs::remove(path, ec); } -bool read_pid(const std::string& path, int64_t& pid) +bool is_plain_path_segment(const std::string& segment) { - std::string text; - if (!read_file(path, text)) + if (segment.empty() || segment == "." || segment == "..") return false; - char* end = nullptr; - const long long value = std::strtoll(text.c_str(), &end, 10); - if (end == text.c_str() || value <= 0) - return false; - pid = static_cast(value); - return true; + return std::all_of(segment.begin(), segment.end(), [](char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || + c == '+' || c == '-'; + }); } -bool process_is_alive(int64_t pid) -{ - if (pid <= 0) - return false; #ifdef _WIN32 - HANDLE handle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, static_cast(pid)); - if (handle == nullptr) - return false; - DWORD exit_code = 0; - const bool alive = ::GetExitCodeProcess(handle, &exit_code) != 0 && exit_code == STILL_ACTIVE; +using LockHandle = HANDLE; +#else +using LockHandle = int; +#endif + +// The install locks this process holds, by path. A lock lives as long as its open +// handle, so the OS drops it when the holder exits, even if it crashed. +std::map& held_install_locks() +{ + static std::map locks; + return locks; +} + +std::mutex& held_install_locks_mutex() +{ + static std::mutex mutex; + return mutex; +} + +void close_lock_file(LockHandle handle) +{ +#ifdef _WIN32 ::CloseHandle(handle); - return alive; #else - if (::kill(static_cast(pid), 0) == 0) - return true; - return errno == EPERM; + ::close(handle); #endif } -int64_t current_process_id() -{ -#ifdef _WIN32 - return static_cast(::_getpid()); -#else - return static_cast(::getpid()); -#endif -} - -bool create_lock_file(const std::string& path, int64_t owner_pid) +// Takes the exclusive lock without waiting and writes owner_pid into the file. False when +// another handle holds the lock. +bool open_lock_file(const std::string& path, int64_t owner_pid, LockHandle& out) { const std::string text = std::to_string(owner_pid); #ifdef _WIN32 - const int fd = ::_wopen(boost::nowide::widen(path).c_str(), _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE); + const HANDLE handle = ::CreateFileW(boost::nowide::widen(path).c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) + return false; + OVERLAPPED overlapped = {}; + if (!::LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped)) { + ::CloseHandle(handle); + return false; + } + DWORD written = 0; + ::SetFilePointer(handle, 0, nullptr, FILE_BEGIN); + ::SetEndOfFile(handle); + if (!::WriteFile(handle, text.data(), static_cast(text.size()), &written, nullptr) || written != text.size()) { + ::CloseHandle(handle); + return false; + } + out = handle; + return true; #else - const int fd = ::open(path.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0644); -#endif + const int fd = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644); if (fd < 0) return false; -#ifdef _WIN32 - const int written = ::_write(fd, text.data(), static_cast(text.size())); - ::_close(fd); -#else - const ssize_t written = ::write(fd, text.data(), text.size()); - ::close(fd); + if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + ::close(fd); + return false; + } + // The file may have been removed between open and flock. A lock on that file excludes nobody. + struct stat opened = {}; + struct stat current = {}; + if (::fstat(fd, &opened) != 0 || ::stat(path.c_str(), ¤t) != 0 || opened.st_dev != current.st_dev || + opened.st_ino != current.st_ino) { + ::close(fd); + return false; + } + if (::ftruncate(fd, 0) != 0 || ::write(fd, text.data(), text.size()) != static_cast(text.size())) { + ::close(fd); + return false; + } + out = fd; + return true; #endif - return written == static_cast(text.size()); } bool read_install_record_file(InstallRecord& out) @@ -309,10 +336,21 @@ DownloadPrep prepare_download_dir(const std::string& dir, return prep; } -bool is_release_download_url(const std::string& url) +bool is_release_download_url(const std::string& url, const std::string& asset_name) { static const std::string prefix = "https://github.com/OrcaSlicer/OrcaSlicer/releases/download/"; - return url.compare(0, prefix.size(), prefix) == 0; + if (asset_name.empty() || url.compare(0, prefix.size(), prefix) != 0) + return false; + + // Exactly /: no other path segment, query, fragment or escape can + // reach a different repository path once curl normalizes the URL. + const std::string rest = url.substr(prefix.size()); + const std::string::size_type slash = rest.find('/'); + if (slash == std::string::npos || rest.find('/', slash + 1) != std::string::npos) + return false; + const std::string tag = rest.substr(0, slash); + const std::string name = rest.substr(slash + 1); + return name == asset_name && is_plain_path_segment(tag) && is_plain_path_segment(name); } std::string handoff_to_json(const UpdateHandoff& handoff) @@ -387,6 +425,7 @@ std::string install_record_to_json(const InstallRecord& record) j["digest"] = record.digest; j["channel"] = record.channel; j["version"] = record.version; + j["target"] = record.target; return j.dump(); } @@ -404,6 +443,7 @@ bool install_record_from_json(const std::string& text, InstallRecord& out) out.digest = text_field(j, "digest"); out.channel = text_field(j, "channel"); out.version = text_field(j, "version"); + out.target = text_field(j, "target"); return true; } @@ -412,14 +452,14 @@ bool write_install_record(const InstallRecord& record) return write_file_atomic(updater_install_record_path(), install_record_to_json(record)); } -bool take_install_record(InstallRecord& out) +bool read_install_record(InstallRecord& out) +{ + return read_install_record_file(out); +} + +void remove_install_record() { - InstallRecord record; - if (!read_install_record_file(record)) - return false; - out = record; remove_file(updater_install_record_path()); - return true; } std::string pending_install_to_json(const PendingInstall& pending) @@ -472,26 +512,27 @@ void remove_pending_install() bool acquire_install_lock(const std::string& path, int64_t owner_pid) { - ensure_parent_dir(path); - if (create_lock_file(path, owner_pid)) - return true; - - int64_t existing_pid = 0; - if (read_pid(path, existing_pid) && process_is_alive(existing_pid)) + std::lock_guard guard(held_install_locks_mutex()); + if (held_install_locks().count(path) != 0) return false; - - remove_file(path); - return create_lock_file(path, owner_pid); + ensure_parent_dir(path); + LockHandle handle{}; + if (!open_lock_file(path, owner_pid, handle)) + return false; + held_install_locks().emplace(path, handle); + return true; } void release_install_lock(const std::string& path) { - int64_t held_pid = 0; - if (!read_pid(path, held_pid)) - return; - if (held_pid != current_process_id()) + std::lock_guard guard(held_install_locks_mutex()); + const auto it = held_install_locks().find(path); + if (it == held_install_locks().end()) return; + // Removed while still locked, so a waiter that gets the lock next finds the path gone. remove_file(path); + close_lock_file(it->second); + held_install_locks().erase(it); } } // namespace Slic3r diff --git a/src/libslic3r/UpdateHandoff.hpp b/src/libslic3r/UpdateHandoff.hpp index a782c135bf..7f178329e2 100644 --- a/src/libslic3r/UpdateHandoff.hpp +++ b/src/libslic3r/UpdateHandoff.hpp @@ -7,7 +7,7 @@ // handoff.json app writes, helper reads once and deletes // installed.json helper writes, app reads on its next start // pending.json helper writes before swapping, app deletes after it starts -// install.lock app creates to claim the install, helper releases +// install.lock app locks it to claim the install, helper takes it over once the app exits // downloads/ partial and verified artifacts // helper/ the helper, extracted so it can outlive the app // updater.log helper log @@ -49,6 +49,7 @@ struct InstallRecord std::string digest; // the installed artifact's digest std::string channel; // channel it came from std::string version; + std::string target; // install dir or .app bundle the install wrote to }; // Written before the swap, so that a crash between "old moved aside" and "new @@ -94,8 +95,9 @@ DownloadPrep prepare_download_dir(const std::string& dir, const std::string& digest, int64_t expected_size); -// Only https downloads from the OrcaSlicer release page are fetched and installed. -bool is_release_download_url(const std::string& url); +// Only https downloads of `asset_name` from the OrcaSlicer release page, at +// releases/download//, are fetched and installed. +bool is_release_download_url(const std::string& url, const std::string& asset_name); std::string handoff_to_json(const UpdateHandoff& handoff); bool handoff_from_json(const std::string& json, UpdateHandoff& out); @@ -106,8 +108,9 @@ void remove_handoff(); std::string install_record_to_json(const InstallRecord& record); bool install_record_from_json(const std::string& json, InstallRecord& out); bool write_install_record(const InstallRecord& record); -// Reads and deletes the record. Returns false when there is none. -bool take_install_record(InstallRecord& out); +// Returns false when there is none. The record is left in place. +bool read_install_record(InstallRecord& out); +void remove_install_record(); std::string pending_install_to_json(const PendingInstall& pending); bool pending_install_from_json(const std::string& json, PendingInstall& out); @@ -115,9 +118,10 @@ bool write_pending_install(const PendingInstall& pending); bool read_pending_install(PendingInstall& out); void remove_pending_install(); -// Creates the install lock holding this process id. False when another install -// already holds it and its owner is still alive (a stale lock is taken over). +// Takes an OS file lock on the install lock, which the holder keeps until it exits, and +// writes owner_pid into the file. False when another handle holds the lock. bool acquire_install_lock(const std::string& path, int64_t owner_pid); +// Unlocks and deletes the file this process acquired. A no-op for any other path. void release_install_lock(const std::string& path); } // namespace Slic3r diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 9345c42938..bdeb54a01a 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -3499,19 +3499,25 @@ bool GUI_App::on_init_inner() update_is_skipped(m_update_candidate, app_config->get("skip_version"), app_config->skip_artifact())) return; - UpdateVersionDialog dialog(this->mainframe); - wxString channel_label; - switch (m_update_candidate.channel) { - case UpdateChannel::PreRelease: channel_label = _L("Pre-Release channel"); break; - case UpdateChannel::Nightly: channel_label = _L("Nightly channel"); break; - case UpdateChannel::Stable: channel_label = _L("Stable channel"); break; + // Destroyed before the action runs: the in-app update closes the main frame, which + // would otherwise delete the dialog as a child and then again at scope exit. + int answer = wxID_CANCEL; + { + UpdateVersionDialog dialog(this->mainframe); + wxString channel_label; + switch (m_update_candidate.channel) { + case UpdateChannel::PreRelease: channel_label = _L("Pre-Release channel"); break; + case UpdateChannel::Nightly: channel_label = _L("Nightly channel"); break; + case UpdateChannel::Stable: channel_label = _L("Stable channel"); break; + } + dialog.set_channel_label(channel_label); + dialog.set_release_url(wxString::FromUTF8(m_update_candidate.release_url)); + dialog.set_install_in_app(can_install_in_app(m_update_candidate, current_install_flavour())); + dialog.update_version_info(wxString::FromUTF8(m_update_candidate.release_notes), + wxString::FromUTF8(m_update_candidate.version_label)); + answer = dialog.ShowModal(); } - dialog.set_channel_label(channel_label); - dialog.set_release_url(wxString::FromUTF8(m_update_candidate.release_url)); - dialog.set_install_in_app(can_install_in_app(m_update_candidate, current_install_flavour())); - dialog.update_version_info(wxString::FromUTF8(m_update_candidate.release_notes), - wxString::FromUTF8(m_update_candidate.version_label)); - switch (dialog.ShowModal()) { + switch (answer) { case wxID_YES: { // Store builds get updates from the Microsoft Store and Flatpak builds from Flathub. // Download-only installs open the asset itself. An install without a verifiable @@ -3523,7 +3529,8 @@ bool GUI_App::on_init_inner() open_ms_store_product_page(); else if (flavour == InstallFlavour::Flatpak) wxLaunchDefaultBrowser(from_u8(flathub_app_url)); - else if (is_download_only(flavour) && is_release_download_url(m_update_candidate.asset.url)) + else if (is_download_only(flavour) && + is_release_download_url(m_update_candidate.asset.url, m_update_candidate.asset.name)) wxLaunchDefaultBrowser(from_u8(m_update_candidate.asset.url)); else wxLaunchDefaultBrowser(from_u8(m_update_candidate.release_url)); @@ -6980,10 +6987,10 @@ void GUI_App::finish_pending_update() { set_updater_cache_dir(update_cache_dir()); - // The helper writes this only before the new build starts, so it is safe to take even - // while the helper still holds the install lock. + // The record is shared by every copy of the app in this cache. Only the copy it names + // acts on it; the others leave it in place. InstallRecord record; - const bool has_record = take_install_record(record); + const bool has_record = read_install_record(record) && !record.target.empty() && running_from(record.target); if (has_record) app_config->set_installed_build(record.channel, record.digest); @@ -7039,8 +7046,10 @@ void GUI_App::finish_pending_update() remove_pending_install(); } - if (has_record) + if (has_record) { + remove_install_record(); clear_install_leftovers(); + } release_install_lock(lock_path); } diff --git a/src/slic3r/UpdateHelper/HttpDownloader.cpp b/src/slic3r/UpdateHelper/HttpDownloader.cpp index 2ba00b3f56..9c45cef024 100644 --- a/src/slic3r/UpdateHelper/HttpDownloader.cpp +++ b/src/slic3r/UpdateHelper/HttpDownloader.cpp @@ -237,6 +237,7 @@ DownloadResult HttpDownloader::download(const std::string& url, curl_easy_setopt(curl, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS)); curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS)); #endif + curl_easy_setopt(curl, CURLOPT_PATH_AS_IS, 1L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, kMaxRedirects); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); diff --git a/src/slic3r/UpdateHelper/apply_macos.cpp b/src/slic3r/UpdateHelper/apply_macos.cpp index 7f6b56166a..44ff697c6c 100644 --- a/src/slic3r/UpdateHelper/apply_macos.cpp +++ b/src/slic3r/UpdateHelper/apply_macos.cpp @@ -135,10 +135,7 @@ bool path_exists(const std::string& path) return boost::filesystem::exists(boost::filesystem::path(path), ec); } -// Move pairs of paths as the administrator, through one Finder-style prompt. -// Returns true only when the script exits 0; callers read the filesystem for how -// far a failed run got. -bool elevated_moves(const std::vector>& moves, std::string& error) +std::string move_script(const std::vector>& moves) { std::string script; for (const auto& move : moves) { @@ -146,7 +143,14 @@ bool elevated_moves(const std::vector>& move script += " && "; script += "/bin/mv -f " + shell_quoted(move.first) + " " + shell_quoted(move.second); } + return script; +} +// Runs `script` as the administrator, through one Finder-style prompt. +// Returns true only when the script exits 0; callers read the filesystem for how +// far a failed run got. +bool elevated_script(const std::string& script, std::string& error) +{ const std::vector argv = { "/usr/bin/osascript", "-e", @@ -162,6 +166,12 @@ bool elevated_moves(const std::vector>& move return true; } +// Move pairs of paths as the administrator, through one Finder-style prompt. +bool elevated_moves(const std::vector>& moves, std::string& error) +{ + return elevated_script(move_script(moves), error); +} + std::string find_mounted_app(const std::string& mount) { std::string fallback; @@ -201,6 +211,18 @@ struct MountGuard ~MountGuard() { release(); } }; +// The new build staged outside the target's parent, needed only until the install ends. +struct ScratchGuard +{ + std::string path; + + ~ScratchGuard() + { + if (!path.empty()) + remove_path_quietly(path); + } +}; + } // namespace bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifact_path, ProgressSink& sink, std::string& error) @@ -225,6 +247,13 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa const std::string staged = bundle + ".staged-" + pid; const std::string backup = bundle + ".backup-" + pid; const std::string download_folder = boost::filesystem::path(artifact_path).parent_path().string(); + const std::string parent = boost::filesystem::path(bundle).parent_path().string(); + const bool parent_writable = ::access(parent.c_str(), W_OK) == 0; + // Where the new build is staged before the swap. A parent the user cannot write + // (a system-wide install) gets it from the cache, copied in by the administrator step. + const std::string scratch = parent_writable + ? staged + : (boost::filesystem::path(handoff.cache_dir) / boost::filesystem::path(staged).filename()).string(); boost::system::error_code ec; if (!boost::filesystem::is_directory(boost::filesystem::path(bundle), ec)) { @@ -240,6 +269,7 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa MountGuard guard; guard.mount = "/tmp/orca-updater-" + pid; + ScratchGuard scratch_guard{parent_writable ? std::string() : scratch}; boost::system::error_code mkdir_ec; boost::filesystem::create_directories(boost::filesystem::path(guard.mount), mkdir_ec); if (!boost::filesystem::is_directory(boost::filesystem::path(guard.mount), mkdir_ec)) { @@ -279,12 +309,12 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa } sink.say(Stage::Installing, 40, "Preparing " + label); - if (!spawn_and_wait({"/usr/bin/ditto", mounted_app, staged}, 900, status, error)) { - remove_path_quietly(staged); + if (!spawn_and_wait({"/usr/bin/ditto", mounted_app, scratch}, 900, status, error)) { + remove_path_quietly(scratch); return false; } - if (status != 0 || !path_exists(staged)) { - remove_path_quietly(staged); + if (status != 0 || !path_exists(scratch)) { + remove_path_quietly(scratch); error = "The new version could not be copied out of the disk image."; return false; } @@ -298,7 +328,7 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa pending.channel = handoff.channel; pending.version = handoff.version; if (!write_pending_install(pending)) { - remove_path_quietly(staged); + remove_path_quietly(scratch); error = "The update could not be recorded, so nothing was changed."; return false; } @@ -355,41 +385,58 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa sink.say(Stage::Installing, 70, "Replacing the application"); - ec.clear(); - boost::filesystem::rename(boost::filesystem::path(bundle), boost::filesystem::path(backup), ec); - if (ec) { - if (ec.value() != EACCES && ec.value() != EPERM) { - error = rollback_failure("The current application could not be moved aside: " + ec.message() + "."); - return false; - } - // A system-wide install: one administrator prompt does both moves. After a - // failed run, what happened is read from which paths still exist. - elevated = true; - if (!elevated_moves({{bundle, backup}, {staged, bundle}}, error)) { + if (!parent_writable) { + // One administrator prompt copies the new build in beside the old one and swaps + // both; the swap itself is a rename inside the target's parent. + const std::string copy = "/usr/bin/ditto " + shell_quoted(scratch) + " " + shell_quoted(staged); + if (!elevated_script(copy + " && " + move_script({{bundle, backup}, {staged, bundle}}), error)) { + // Nothing moved aside means nothing for the administrator to put back, so no second prompt. moved_old = path_exists(backup); - placed_new = !path_exists(staged); + placed_new = moved_old && path_exists(bundle); + elevated = moved_old; error = rollback_failure(error + " The downloaded disk image is still in " + download_folder + "."); return false; } + elevated = true; moved_old = true; placed_new = true; } else { - moved_old = true; ec.clear(); - boost::filesystem::rename(boost::filesystem::path(staged), boost::filesystem::path(bundle), ec); - if (!ec) { - placed_new = true; - } else if (ec.value() == EACCES || ec.value() == EPERM) { + boost::filesystem::rename(boost::filesystem::path(bundle), boost::filesystem::path(backup), ec); + if (ec) { + if (ec.value() != EACCES && ec.value() != EPERM) { + error = rollback_failure("The current application could not be moved aside: " + ec.message() + "."); + return false; + } + // A system-wide install: one administrator prompt does both moves. After a + // failed run, what happened is read from which paths still exist. elevated = true; - if (!elevated_moves({{staged, bundle}}, error)) { + if (!elevated_moves({{bundle, backup}, {staged, bundle}}, error)) { + moved_old = path_exists(backup); placed_new = !path_exists(staged); error = rollback_failure(error + " The downloaded disk image is still in " + download_folder + "."); return false; } + moved_old = true; placed_new = true; } else { - error = rollback_failure("The new version could not be put in place: " + ec.message() + "."); - return false; + moved_old = true; + ec.clear(); + boost::filesystem::rename(boost::filesystem::path(staged), boost::filesystem::path(bundle), ec); + if (!ec) { + placed_new = true; + } else if (ec.value() == EACCES || ec.value() == EPERM) { + elevated = true; + if (!elevated_moves({{staged, bundle}}, error)) { + placed_new = !path_exists(staged); + error = rollback_failure(error + " The downloaded disk image is still in " + download_folder + "."); + return false; + } + placed_new = true; + } else { + error = rollback_failure("The new version could not be put in place: " + ec.message() + "."); + return false; + } } } @@ -403,6 +450,7 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa record.digest = handoff.digest; record.channel = handoff.channel; record.version = handoff.version; + record.target = bundle; if (!write_install_record(record)) { error = rollback_failure("The update could not be recorded."); return false; diff --git a/src/slic3r/UpdateHelper/apply_windows.cpp b/src/slic3r/UpdateHelper/apply_windows.cpp index d13d82ae01..43944dd40f 100644 --- a/src/slic3r/UpdateHelper/apply_windows.cpp +++ b/src/slic3r/UpdateHelper/apply_windows.cpp @@ -12,13 +12,17 @@ #include #include #include + #include #if defined(_MSC_VER) #pragma comment(lib, "wintrust.lib") #endif + #include #include + #include #include + #include #include #include @@ -154,6 +158,47 @@ bool run_installer(const std::string& artifact_path, const std::string& install_ return true; } +// True when a process other than this one runs an image under install_root. +// Such a process keeps files locked, and the silent NSIS installer would +// uninstall first and then fail halfway. +bool other_instance_running(const std::string& install_root) +{ + std::wstring prefix = widen_utf8(install_root); + for (wchar_t& ch : prefix) + if (ch == L'/') + ch = L'\\'; + while (!prefix.empty() && prefix.back() == L'\\') + prefix.pop_back(); + if (prefix.empty()) + return false; + prefix += L'\\'; + + const HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snapshot == INVALID_HANDLE_VALUE) + return false; + + const DWORD self = ::GetCurrentProcessId(); + bool found = false; + PROCESSENTRY32W entry; + entry.dwSize = sizeof(entry); + for (BOOL more = ::Process32FirstW(snapshot, &entry); more && !found; more = ::Process32NextW(snapshot, &entry)) { + if (entry.th32ProcessID == self) + continue; + const HANDLE process = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ProcessID); + if (process == nullptr) + continue; + std::wstring image(32768, L'\0'); + DWORD size = static_cast(image.size()); + if (::QueryFullProcessImageNameW(process, 0, image.data(), &size)) { + image.resize(size); + found = image.size() >= prefix.size() && _wcsnicmp(image.c_str(), prefix.c_str(), prefix.size()) == 0; + } + ::CloseHandle(process); + } + ::CloseHandle(snapshot); + return found; +} + } // namespace bool apply_windows_install(const UpdateHandoff& handoff, const std::string& artifact_path, ProgressSink& sink, std::string& error) @@ -182,6 +227,22 @@ bool apply_windows_install(const UpdateHandoff& handoff, const std::string& arti return false; } + if (other_instance_running(install_root)) { + sink.say(Stage::Installing, 0, "Waiting for other OrcaSlicer windows to close"); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (other_instance_running(install_root)) { + if (sink.cancelled && sink.cancelled()) { + error = "cancelled"; + return false; + } + if (std::chrono::steady_clock::now() >= deadline) { + error = "Another OrcaSlicer window is still open. Close all OrcaSlicer windows, then try the update again."; + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + } + // No backup folder here on purpose: the installer removes and rewrites // the whole tree itself, and a pre-rename would make its uninstall // step fail. The pending record still marks the install as in flight. @@ -209,6 +270,7 @@ bool apply_windows_install(const UpdateHandoff& handoff, const std::string& arti record.digest = handoff.digest; record.channel = handoff.channel; record.version = handoff.version; + record.target = install_root; if (!write_install_record(record)) BOOST_LOG_TRIVIAL(warning) << "Could not record the installed build " << handoff.version; diff --git a/src/slic3r/UpdateHelper/main.cpp b/src/slic3r/UpdateHelper/main.cpp index 6b36ee6bd4..8f87634ae9 100644 --- a/src/slic3r/UpdateHelper/main.cpp +++ b/src/slic3r/UpdateHelper/main.cpp @@ -112,8 +112,8 @@ bool UpdateHelperApp::OnInit() Slic3r::set_updater_cache_dir(handoff.cache_dir); // Handed to the frame, which takes it only once the parent has exited: the - // application still owns it while it is closing down. The single release - // stays in the app, so every exit path frees it. + // application still owns it while it is closing down. The helper releases it + // on every exit path; a lock it never took is a no-op to release. m_lock_path = handoff.lock_path.empty() ? Slic3r::updater_lock_path() : handoff.lock_path; handoff.lock_path = m_lock_path; @@ -125,7 +125,7 @@ bool UpdateHelperApp::OnInit() fs::remove(path, ec); } - if (!Slic3r::is_release_download_url(handoff.url)) { + if (!Slic3r::is_release_download_url(handoff.url, handoff.asset_name)) { release_lock(); Slic3r::Updater::relaunch_app(handoff); wxMessageBox("The update information is incomplete or does not point to an OrcaSlicer release.", kDialogTitle, diff --git a/tests/libslic3r/update_channel_tests.cpp b/tests/libslic3r/update_channel_tests.cpp index f85cbbe16b..d09cda718b 100644 --- a/tests/libslic3r/update_channel_tests.cpp +++ b/tests/libslic3r/update_channel_tests.cpp @@ -670,6 +670,49 @@ TEST_CASE("A source build has no nightly identity to compare against", "[UpdateC CHECK(candidate.reason == "source_build"); } +TEST_CASE("A nightly built shortly before its release's last asset upload is not offered to itself", "[UpdateChannel]") +{ + // The release is updated_at 2026-11-10T08:31:54Z; the build started an hour earlier. + const UpdateCandidate candidate = resolve_update(nightly_releases_json(), UpdateChannel::Nightly, "", "", + "2.6.0-dev", "2026-11-10T07:31:54Z", + InstallFlavour::WindowsInstaller, "x86_64"); + + CHECK_FALSE(candidate.available); + CHECK(candidate.reason == "up_to_date"); +} + +TEST_CASE("A nightly released well after the build is offered to a manually installed build", "[UpdateChannel]") +{ + // Twelve hours before the release, which is past the upload margin. + const UpdateCandidate candidate = resolve_update(nightly_releases_json(), UpdateChannel::Nightly, "", "", + "2.6.0-dev", "2026-11-09T20:31:54Z", + InstallFlavour::WindowsInstaller, "x86_64"); + + CHECK(candidate.available); + CHECK(candidate.reason.empty()); + CHECK(candidate.asset.digest == "sha256:nightly2"); +} + +TEST_CASE("A nightly built after its release is not offered to a manually installed build", "[UpdateChannel]") +{ + const UpdateCandidate candidate = resolve_update(nightly_releases_json(), UpdateChannel::Nightly, "", "", + "2.6.0-dev", "2026-11-10T09:00:00Z", + InstallFlavour::WindowsInstaller, "x86_64"); + + CHECK_FALSE(candidate.available); + CHECK(candidate.reason == "up_to_date"); +} + +TEST_CASE("A nightly with an unparsable build timestamp is not offered to a manually installed build", "[UpdateChannel]") +{ + const UpdateCandidate candidate = resolve_update(nightly_releases_json(), UpdateChannel::Nightly, "", "", + "2.6.0-dev", "not-a-timestamp", + InstallFlavour::WindowsInstaller, "x86_64"); + + CHECK_FALSE(candidate.available); + CHECK(candidate.reason == "up_to_date"); +} + TEST_CASE("A skipped stable version stays skipped until a newer one appears", "[UpdateChannel]") { const UpdateCandidate candidate = resolve_update(stable_releases_json(), UpdateChannel::Stable, "", "", diff --git a/tests/libslic3r/update_handoff_tests.cpp b/tests/libslic3r/update_handoff_tests.cpp index 084e3ca501..af435bfc11 100644 --- a/tests/libslic3r/update_handoff_tests.cpp +++ b/tests/libslic3r/update_handoff_tests.cpp @@ -216,13 +216,71 @@ TEST_CASE("A leftover partial download that cannot be removed is not recorded fo CHECK_FALSE(fs::exists(marker_path(dir.path()))); } -TEST_CASE("Only https release downloads from the OrcaSlicer repository are accepted", "[UpdateHandoff]") +TEST_CASE("A release download of the named asset from the OrcaSlicer repository is accepted", "[UpdateHandoff]") { - CHECK(is_release_download_url("https://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.5.0/app.AppImage")); - CHECK_FALSE(is_release_download_url("")); - CHECK_FALSE(is_release_download_url("http://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.5.0/app.AppImage")); - CHECK_FALSE(is_release_download_url("https://github.com/someone/OrcaSlicer/releases/download/v2.5.0/app.AppImage")); - CHECK_FALSE(is_release_download_url("https://example.com/https://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.5.0/app")); + const std::string release = "https://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.5.0/"; + CHECK(is_release_download_url(release + kAsset, kAsset)); + CHECK_FALSE(is_release_download_url(release + "other.AppImage", kAsset)); + CHECK_FALSE(is_release_download_url(release + kAsset, "")); +} + +TEST_CASE("Release URLs that leave the release path or name another file are rejected", "[UpdateHandoff]") +{ + const std::string release = "https://github.com/OrcaSlicer/OrcaSlicer/releases/download/"; + const std::string asset = kAsset; + const std::string url = GENERATE(as{}, + "", + "http://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.5.0/" + asset, + "https://github.com/someone/OrcaSlicer/releases/download/v2.5.0/" + asset, + "https://example.com/https://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.5.0/" + asset, + release + "../../../evil/x/releases/download/v1/" + asset, + release + "../" + asset, + release + "%2e%2e/" + asset, + release + "v2.5.0\\evil/" + asset, + release + "v2.5.0@evil.example/" + asset, + release + "v2.5.0/" + asset + "?query=1", + release + "v2.5.0/" + asset + "#frag", + release + "v2.5.0/" + asset + "/extra", + release + "/" + asset, + release + "v2.5.0/", + release + "v2.5.0/other.AppImage"); + CHECK_FALSE(is_release_download_url(url, asset)); +} + +TEST_CASE("A second install lock on the same path is refused while the first is held", "[UpdateHandoff]") +{ + ScopedTemporaryDir dir; + const std::string lock = (dir.path() / "install.lock").string(); + + CHECK(acquire_install_lock(lock, 1234)); + CHECK_FALSE(acquire_install_lock(lock, 5678)); + CHECK(read_text(lock) == "1234"); + + release_install_lock(lock); + CHECK_FALSE(fs::exists(lock)); + CHECK(acquire_install_lock(lock, 5678)); + release_install_lock(lock); +} + +TEST_CASE("A leftover install lock file that nobody holds is taken over", "[UpdateHandoff]") +{ + ScopedTemporaryDir dir; + const std::string lock = (dir.path() / "install.lock").string(); + write_text(lock, "99999"); + + CHECK(acquire_install_lock(lock, 1234)); + CHECK(read_text(lock) == "1234"); + release_install_lock(lock); +} + +TEST_CASE("Releasing an install lock this process does not hold leaves the file in place", "[UpdateHandoff]") +{ + ScopedTemporaryDir dir; + const std::string lock = (dir.path() / "install.lock").string(); + write_text(lock, "1234"); + + release_install_lock(lock); + CHECK(fs::exists(lock)); } TEST_CASE("The handoff round-trips through a cache directory with non-ASCII characters", "[UpdateHandoff]") @@ -244,3 +302,54 @@ TEST_CASE("The handoff round-trips through a cache directory with non-ASCII char clear_updater_cache_dir(); } + +TEST_CASE("An install record round-trips with the install it describes", "[UpdateHandoff]") +{ + InstallRecord written; + written.digest = kDigest; + written.channel = "stable"; + written.version = "2.5.0"; + written.target = "/opt/OrcaSlicer"; + + InstallRecord read; + CHECK(install_record_from_json(install_record_to_json(written), read)); + CHECK(read.digest == written.digest); + CHECK(read.channel == written.channel); + CHECK(read.version == written.version); + CHECK(read.target == written.target); +} + +TEST_CASE("An install record without a target parses with an empty target", "[UpdateHandoff]") +{ + InstallRecord read; + CHECK(install_record_from_json(R"({"digest":"sha256:1111","channel":"stable","version":"2.5.0"})", read)); + CHECK(read.digest == kDigest); + CHECK(read.target.empty()); +} + +TEST_CASE("Reading the install record leaves it in place and removing it deletes it", "[UpdateHandoff]") +{ + ScopedTemporaryDir dir; + set_updater_cache_dir(dir.string()); + + InstallRecord written; + written.digest = kDigest; + written.target = "/opt/OrcaSlicer"; + CHECK(write_install_record(written)); + + InstallRecord first; + CHECK(read_install_record(first)); + CHECK(first.target == written.target); + CHECK(fs::exists(updater_install_record_path())); + + InstallRecord second; + CHECK(read_install_record(second)); + CHECK(second.digest == kDigest); + + remove_install_record(); + CHECK_FALSE(fs::exists(updater_install_record_path())); + InstallRecord gone; + CHECK_FALSE(read_install_record(gone)); + + clear_updater_cache_dir(); +}