diff --git a/build_release_macos.sh b/build_release_macos.sh index 7a9ddb5677..e2612ed7ad 100755 --- a/build_release_macos.sh +++ b/build_release_macos.sh @@ -412,9 +412,19 @@ function build_slicer() { # release does not use, and nothing in the bundle would say so. The # configure wrote what it baked in, so the two are compared here. signing_stamp="$PROJECT_BUILD_DIR/updater-signing.txt" + # A pin the environment does not name is whatever the tree was configured + # with: version.inc keeps the cached value when the variable is unset, so + # comparing against an unset environment would reject a helper that is + # exactly what this tree builds. + cached_pin() { + [ -f "$PROJECT_BUILD_DIR/CMakeCache.txt" ] || return 0 + sed -n "s/^$1:[A-Z]*=//p" "$PROJECT_BUILD_DIR/CMakeCache.txt" | head -n 1 + } expected_signing=$(printf 'publisher=%s\nteam_id=%s\nsig_key=%s\ntimestamp=%s\n' \ - "${ORCA_UPDATER_PUBLISHER:-}" "${ORCA_UPDATER_TEAM_ID:-}" \ - "${ORCA_UPDATER_SIG_KEY:-}" "${ORCA_BUILD_TIMESTAMP:-}") + "${ORCA_UPDATER_PUBLISHER:-$(cached_pin ORCA_UPDATER_PUBLISHER)}" \ + "${ORCA_UPDATER_TEAM_ID:-$(cached_pin ORCA_UPDATER_TEAM_ID)}" \ + "${ORCA_UPDATER_SIG_KEY:-$(cached_pin ORCA_UPDATER_SIG_KEY)}" \ + "${ORCA_BUILD_TIMESTAMP:-$(cached_pin ORCA_BUILD_TIMESTAMP)}") if [ ! -f "$signing_stamp" ]; then echo "Error: $signing_stamp is missing, so what the helper accepts is not known." >&2 echo "Reconfigure the tree before packaging it." >&2 @@ -424,7 +434,7 @@ function build_slicer() { echo "Error: the updater helper was built with other signature pins than this package names:" >&2 printf '%s\n' "$expected_signing" \ | diff -u -L "packaged under" -L "built with" - "$signing_stamp" >&2 || true - echo "Reconfigure the tree before packaging it." >&2 + echo "Reconfigure the tree with these ORCA_UPDATER_* values, or unset them and rebuild." >&2 exit 1 fi echo "Copying OrcaSlicerUpdater..." diff --git a/build_win.bat b/build_win.bat index d25ecd3fcb..510f87ccaf 100644 --- a/build_win.bat +++ b/build_win.bat @@ -821,7 +821,10 @@ if "%build_slicer%" == "ON" ( if defined ORCA_SIGN_CERTFILE if defined ORCA_SIGN_KMS_KEY if defined ORCA_SIGN_JSIGN ( set "sign_shell=powershell" where pwsh >nul 2>nul && set "sign_shell=pwsh" - set sign_arg="-DORCA_SIGN_CMD=!sign_shell! -NoProfile -ExecutionPolicy Bypass -File "%WP%\scripts\sign_windows.ps1" -Path" + REM The script path may contain spaces, so it stays its own quoted + REM token and the .nsi builds the command; one command string here + REM would be cut at the first space in the path. + set sign_arg="-DORCA_SIGN_SHELL=!sign_shell!" "-DORCA_SIGN_SCRIPT=%WP%\scripts\sign_windows.ps1" ) call :print_and_run "!nsis_exe!" /V3 "-DSTAGE=!installer_stage!" "-DOUTFILE=!installer_out!" "-DAPP_VERSION=!orca_version!" !sign_arg! "%WP%\packaging\windows\orca-slicer.nsi" diff --git a/docs/HLSD/updater.md b/docs/HLSD/updater.md index 3c1f8b3f07..b43b67fe07 100644 --- a/docs/HLSD/updater.md +++ b/docs/HLSD/updater.md @@ -135,13 +135,14 @@ the application runs from; the extracted helper and the handoff that names the j keyed the same way. Two installs share one cache, and each one downloads the artifact for its own platform and channel: a single directory would let one install consume a file the other had verified, run a helper the other extracted, or overwrite the job the other had -handed to its helper. +handed to its helper. The pending-swap record is keyed the same way, so one install cannot +settle or delete the recovery record of another. | File | Written by | Read by | Purpose | |---|---|---|---| -| `handoff-.json` | app | helper, once | the job: asset, digest, size, install root, parent pid, lock path | +| `handoff--.json` | app | helper, once | the job: asset, digest, size, install root, parent pid, lock path. A prefetch and an install each get their own, so neither consumes the other's | | `installed.json` | helper | app, next start | what was installed, and the tree it belongs to | -| `pending.json` | helper, before the swap | app, next start | the swap in flight; on macOS the tree moved aside, for rollback and cleanup | +| `pending-.json` | helper, before the swap | app, next start | the swap in flight; on macOS the tree moved aside, for rollback and cleanup | | `install.lock` | app, then helper | both | an OS file lock held for the life of the holder | | `download.lock` | prefetch helper | app, skip path | held while a prefetch writes; a skip defers its cleanup while it is held | | `.verified` | prefetch helper, after verification | app | the digest the artifact verified for | @@ -165,7 +166,9 @@ The lock is an OS-level lock on an open handle, not a pid file: the OS releases when the holder dies, and a held lock cannot be read through another handle, so it carries no state. It prevents two installs, and the cleanup respects it. A second lock in the download directory is held by the prefetch while it writes, so a skip's cleanup and an -install that follows a click both wait or refuse rather than race it. +install that follows a click both wait or refuse rather than race it. The helper releases +it once the new build is in place and recorded, before it starts it: the new build's own +startup settles those records, and must not find the lock held. ## Installing @@ -267,7 +270,9 @@ on the user reading a dialog: query, no other segment. The downloader keeps curl from normalising the path and accepts redirects only to https. 2. **Digest.** The artifact's `sha256` from the release listing is checked against the - downloaded bytes. This proves the transfer, not the listing. + downloaded bytes. This proves the transfer, not the listing. A body larger than the + size the listing announces is dropped as it arrives, so it cannot fill the disk before + that check runs. 3. **Signature.** The installer or bundle must verify with the platform's trust service. 4. **Publisher.** The signer must be *ours*: the Authenticode signer's display name on diff --git a/packaging/windows/orca-slicer.nsi b/packaging/windows/orca-slicer.nsi index 98c21b9904..22e1b85f53 100644 --- a/packaging/windows/orca-slicer.nsi +++ b/packaging/windows/orca-slicer.nsi @@ -18,10 +18,12 @@ ; 3 the old tree was removed and the new one could not be put in place ; ; Supplied with -D by the caller: -; STAGE install tree to package (required) -; OUTFILE installer to write (required) -; APP_VERSION version shown in Apps & features (required) -; ORCA_SIGN_CMD signs one file, "%1" is the file (optional) +; STAGE install tree to package (required) +; OUTFILE installer to write (required) +; APP_VERSION version shown in Apps & features (required) +; ORCA_SIGN_CMD signs one file, "%1" is the file (optional) +; ORCA_SIGN_SHELL shell that runs the signing script (optional, with ORCA_SIGN_SCRIPT) +; ORCA_SIGN_SCRIPT signing script the shell runs (optional, with ORCA_SIGN_SHELL) Unicode true @@ -76,6 +78,16 @@ InstallDir "${PER_USER_DIR}" ; The payload is signed before it is compressed, the uninstaller before it is ; written, and the installer last. Callers that build unsigned pass no command. +; A caller whose paths may contain spaces names the shell and the script +; separately: quoting a whole command inside the define would break at the +; first space in the path. +!ifndef ORCA_SIGN_CMD + !ifdef ORCA_SIGN_SCRIPT + !ifdef ORCA_SIGN_SHELL + !define ORCA_SIGN_CMD '${ORCA_SIGN_SHELL} -NoProfile -ExecutionPolicy Bypass -File "${ORCA_SIGN_SCRIPT}" -Path' + !endif + !endif +!endif !ifdef ORCA_SIGN_CMD !system '${ORCA_SIGN_CMD} "${STAGE}"' = 0 !uninstfinalize '${ORCA_SIGN_CMD} "%1"' = 0 @@ -290,13 +302,19 @@ probe_done: fresh_install: ; Nothing is installed here, so there is nothing to remove. RMDir only fails - ; when the chosen folder already holds something, and the rename below then - ; fails too, which leaves the folder as it was and the stage unused. + ; when the chosen folder already holds something, and the rename then fails + ; too, which leaves the folder as it was and the stage unused. RMDir "$INSTDIR" ; SetOutPath made the stage the working directory, and Windows refuses to ; rename a directory the process sits in. Leave it before either rename. SetOutPath "$TEMP" + ; The rename itself is the test: a folder that already held an executable + ; would otherwise satisfy the check below and report a successful install + ; while the stage was never moved. + ClearErrors Rename "$INSTDIR.new" "$INSTDIR" + IfErrors install_failed + IfFileExists "$INSTDIR.new\*.*" install_failed IfFileExists "$INSTDIR\${APP_EXE}" 0 install_failed Goto installed diff --git a/src/libslic3r/UpdateChannel.cpp b/src/libslic3r/UpdateChannel.cpp index 9e475c12b9..f71c7d6437 100644 --- a/src/libslic3r/UpdateChannel.cpp +++ b/src/libslic3r/UpdateChannel.cpp @@ -38,7 +38,12 @@ int64_t integer_field(const json& object, const char* key) auto it = object.find(key); if (it == object.end() || !it->is_number()) return 0; - return it->get(); + // A number above INT64_MAX parses as unsigned and get() throws. + try { + return it->get(); + } catch (const std::exception&) { + return 0; + } } std::string strip_version_prefix(const std::string& tag) @@ -408,7 +413,13 @@ UpdateCandidate resolve_update(const std::string& releases_json, candidate.available = release_is_newer || channel_switch; return candidate; } - if (!installed_artifact.empty() && installed_artifact == candidate.asset.digest) { + // The digest identifies which artifact installed this build. On a channel with + // comparable versions it is trusted only while the release is not newer than the + // running build: a downgrade or a repair leaves the old digest behind, and trusting + // it would hide every newer release. A nightly's version is its release timestamp, + // so its digest is the only identity it has. + if (!installed_artifact.empty() && installed_artifact == candidate.asset.digest && + (channel == UpdateChannel::Nightly || !release_is_newer)) { candidate.reason = "up_to_date"; return candidate; } diff --git a/src/libslic3r/UpdateHandoff.cpp b/src/libslic3r/UpdateHandoff.cpp index 5f868cb68f..c4b06dbad5 100644 --- a/src/libslic3r/UpdateHandoff.cpp +++ b/src/libslic3r/UpdateHandoff.cpp @@ -57,7 +57,12 @@ int64_t integer_field(const json& object, const char* key) auto it = object.find(key); if (it == object.end() || !it->is_number()) return 0; - return it->get(); + // A number above INT64_MAX parses as unsigned and get() throws. + try { + return it->get(); + } catch (const std::exception&) { + return 0; + } } // Parses one of the records below. A file that is not a JSON object is treated as missing, @@ -289,14 +294,17 @@ std::string updater_helper_dir() return (base / install_identity_hex(root)).string(); } -std::string updater_handoff_path() +std::string updater_handoff_path(const std::string& job) { const std::string& root = install_root_override(); - if (root.empty()) - return (fs::path(cache_root()) / "handoff.json").string(); + std::string name = "handoff"; // Keyed like the downloads: two copies share one cache, and one must not overwrite the // job another one has handed to its helper. - return (fs::path(cache_root()) / ("handoff-" + install_identity_hex(root) + ".json")).string(); + if (!root.empty()) + name += "-" + install_identity_hex(root); + if (!job.empty()) + name += "-" + job; + return (fs::path(cache_root()) / (name + ".json")).string(); } std::string updater_install_record_path() @@ -306,7 +314,12 @@ std::string updater_install_record_path() std::string updater_pending_path() { - return (fs::path(cache_root()) / "pending.json").string(); + const std::string& root = install_root_override(); + // Keyed like the downloads: a swap in flight belongs to one install, and another copy + // sharing the cache must not read, settle or delete its recovery record. + if (root.empty()) + return (fs::path(cache_root()) / "pending.json").string(); + return (fs::path(cache_root()) / ("pending-" + install_identity_hex(root) + ".json")).string(); } std::string updater_lock_path() @@ -477,6 +490,8 @@ DownloadPrep prepare_download_dir(const std::string& dir, if (!prep.complete) { own_names.push_back(artifact.filename().string()); own_names.push_back(verified.filename().string()); + // A file that could not be read is set aside for the next run; this sweep is that run. + own_names.push_back(artifact.filename().string() + ".unreadable"); } if (asset_name.empty()) { // The names a download took before it was named after its asset. @@ -572,22 +587,22 @@ bool handoff_from_json(const std::string& text, UpdateHandoff& out) return true; } -bool write_handoff(const UpdateHandoff& handoff) +bool write_handoff(const UpdateHandoff& handoff, const std::string& job) { - return write_file_atomic(updater_handoff_path(), handoff_to_json(handoff)); + return write_file_atomic(updater_handoff_path(job), handoff_to_json(handoff)); } -bool read_handoff(UpdateHandoff& out) +bool read_handoff(UpdateHandoff& out, const std::string& job) { std::string text; - if (!read_file(updater_handoff_path(), text)) + if (!read_file(updater_handoff_path(job), text)) return false; return handoff_from_json(text, out); } -void remove_handoff() +void remove_handoff(const std::string& job) { - remove_file(updater_handoff_path()); + remove_file(updater_handoff_path(job)); } std::string install_record_to_json(const InstallRecord& record) diff --git a/src/libslic3r/UpdateHandoff.hpp b/src/libslic3r/UpdateHandoff.hpp index 9825c4f5e6..e5831d5d27 100644 --- a/src/libslic3r/UpdateHandoff.hpp +++ b/src/libslic3r/UpdateHandoff.hpp @@ -4,14 +4,15 @@ // Handoff between the application and the updater helper, plus the small // records they exchange through the updater cache directory: // -// handoff.json app writes, helper reads once and deletes +// handoff--.json app writes, helper reads once and deletes; one per job, +// so a prefetch and an install never consume each other's // installed.json helper writes, app reads on its next start -// pending.json helper writes before swapping, app deletes after it starts +// pending-.json helper writes before swapping, app deletes after it starts // install.lock app locks it to claim the install, helper takes it over once the app exits // downloads/ partial and verified artifacts, one directory per install // helper/ the helper, extracted so it can outlive the app, one directory // per install (see updater_helper_dir()) -// updater.log helper log +// updater.log helper log, appended across runs // // The cache lives in the OS cache directory, not in the data directory: it holds a // download the user can lose. The helper never resolves it itself, because its environment @@ -80,7 +81,10 @@ std::string updater_download_dir(); // one another install extracted, or delete its folder while a prefetch helper runs from it. // Flat /helper without an install root. The helper never resolves this path itself. std::string updater_helper_dir(); -std::string updater_handoff_path(); +// The job file. `job` separates the two jobs the application can hand out at once: a +// background prefetch and the install it makes possible. Each helper deletes only its +// own file, so neither can consume or delete the other's. Empty names the default file. +std::string updater_handoff_path(const std::string& job = std::string()); std::string updater_install_record_path(); std::string updater_pending_path(); std::string updater_lock_path(); @@ -166,9 +170,9 @@ bool is_release_download_url(const std::string& url, const std::string& asset_na std::string handoff_to_json(const UpdateHandoff& handoff); bool handoff_from_json(const std::string& json, UpdateHandoff& out); -bool write_handoff(const UpdateHandoff& handoff); -bool read_handoff(UpdateHandoff& out); -void remove_handoff(); +bool write_handoff(const UpdateHandoff& handoff, const std::string& job = std::string()); +bool read_handoff(UpdateHandoff& out, const std::string& job = std::string()); +void remove_handoff(const std::string& job = std::string()); std::string install_record_to_json(const InstallRecord& record); bool install_record_from_json(const std::string& json, InstallRecord& out); diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 3e6ad69e30..3b9e757744 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -132,6 +132,7 @@ #include #include #include +#include #include #include #include @@ -3581,27 +3582,15 @@ bool GUI_App::on_init_inner() } // The automatic check never shows a dialog: it downloads quietly and the // notification follows once the artifact is verified. - if (!in_app) { - // prefetch_update() only logs for a flavour that cannot install in place, so - // the user would never hear of the release. Point them at it instead. - if (NotificationManager* notifications = notification_manager()) { - const UpdateCandidate candidate = m_update_candidate; - notifications->push_notification( - NotificationType::CustomNotification, - NotificationManager::NotificationLevel::ImportantNotificationLevel, - _u8L("A new version of OrcaSlicer is available."), - _u8L("Open the download page"), - [candidate](wxEvtHandler*) { - open_update_page(candidate); - return true; - }); - } - m_update_candidate = UpdateCandidate(); + if (!in_app || !prefetch_update()) { + // A flavour that cannot install in place, or a helper that could not even + // start: offer the release through the dialog instead, or the user would + // never hear of it and could not skip it. + notify_update_ready(false); return; } BOOST_LOG_TRIVIAL(info) << "Update " << m_update_candidate.version_label << ": downloading in the background"; - if (prefetch_update()) - start_update_ready_timer(); + start_update_ready_timer(); return; } }); @@ -6654,7 +6643,9 @@ void GUI_App::check_new_version_sf(bool show_tips, int by_user) }); }; if (http_status != 200) { - drop_candidate(); + // The request failed, which says nothing about the release on offer: keep the + // candidate, its notification and its poll rather than discard a verified update. + BOOST_LOG_TRIVIAL(warning) << "Update check answered HTTP " << http_status << "; keeping the current release"; return; } try { @@ -6692,7 +6683,7 @@ void GUI_App::check_new_version_sf(bool show_tips, int by_user) QueueEvent(evt); }); } catch (...) { - drop_candidate(); + BOOST_LOG_TRIVIAL(warning) << "Could not read the update response; keeping the current release"; } }); @@ -6833,6 +6824,13 @@ constexpr const char* updater_helper_bare_name = "OrcaSlicerUpdater"; constexpr const char* updater_helper_name = "OrcaSlicerUpdater"; #endif +// The two jobs a helper can be handed while the other one is still running. Each job has +// its own handoff file, so a prefetch helper cannot consume the install job's file (and +// leave the application closed with no helper to finish), or delete it before the +// installed helper reads it. +constexpr const char* updater_install_job = "install"; +constexpr const char* updater_prefetch_job = "prefetch"; + int64_t current_process_id() { #ifdef _WIN32 @@ -6993,13 +6991,14 @@ UpdateHandoff make_update_handoff(const UpdateCandidate& candidate) // Starts the helper with the handoff and the mode flags it was asked for, from the helper's // own folder: it outlives this process and must not keep the log folder as its working // directory. False when wx could not start it. -bool launch_updater_helper(const std::string& helper, std::initializer_list flags) +bool launch_updater_helper(const std::string& helper, std::initializer_list flags, + const std::string& job) { wxExecuteEnv exec_env; exec_env.cwd = from_u8(updater_helper_dir()); const wxString helper_path = from_u8(helper); - const wxString handoff_path = from_u8(updater_handoff_path()); + const wxString handoff_path = from_u8(updater_handoff_path(job)); std::vector argv; argv.push_back(helper_path.wc_str()); argv.push_back(L"--handoff"); @@ -7020,6 +7019,22 @@ bool running_from(const std::string& path) return !ec && same; } +// True when `backup` names the tree a helper moved aside for `target`: exactly +// ".staged-" or ".backup-". The pending record is a hint about +// what to delete, so any other spelling is ignored rather than acted on. +bool is_moved_aside_tree(const std::string& backup, const std::string& target) +{ + if (backup.empty() || target.empty()) + return false; + auto matches = [&](const char* suffix) { + const std::string prefix = target + suffix; + return backup.size() > prefix.size() && backup.compare(0, prefix.size(), prefix) == 0 && + std::all_of(backup.begin() + static_cast(prefix.size()), backup.end(), + [](char c) { return c >= '0' && c <= '9'; }); + }; + return matches(".staged-") || matches(".backup-"); +} + // A recorded install needs neither the artifact nor its download directory any more: there // is nothing left to resume. The helper's log stays, as the trail of the run that succeeded. void clear_install_leftovers() @@ -7069,13 +7084,13 @@ void GUI_App::set_skip_version(bool skip) } } -void GUI_App::start_in_app_update() +bool GUI_App::start_in_app_update() { // Without an asset there is no URL or digest to hand off; the helper would refuse // the job. The caller opens the Store or the release page instead. if (!can_install_in_app(m_update_candidate, current_install_flavour())) { BOOST_LOG_TRIVIAL(warning) << "Not starting an in-app update: no asset for this installation"; - return; + return false; } set_updater_cache_dir(update_cache_dir()); @@ -7088,7 +7103,7 @@ void GUI_App::start_in_app_update() _L("Wait for the current job to finish before installing this update."), _L("Update in progress"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); - return; + return false; } const std::string lock_path = updater_lock_path(); @@ -7096,7 +7111,7 @@ void GUI_App::start_in_app_update() MessageDialog dlg(this->mainframe, _L("An update is already in progress."), _L("Update in progress"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); - return; + return false; } // A prefetch helper may still be writing this build's .part: a second helper would resume @@ -7108,7 +7123,7 @@ void GUI_App::start_in_app_update() MessageDialog dlg(this->mainframe, _L("The update is still downloading. Try again in a moment."), _L("Update"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); - return; + return false; } const UpdateHandoff handoff = make_update_handoff(m_update_candidate); @@ -7122,15 +7137,16 @@ void GUI_App::start_in_app_update() _L("Update"), wxOK | wxICON_WARNING); dlg.ShowModal(); wxLaunchDefaultBrowser(from_u8(m_update_candidate.release_url)); - return; + // The page has been offered in place of the install, so the dialog is answered. + return true; } - if (!write_handoff(handoff)) { + if (!write_handoff(handoff, updater_install_job)) { release_install_lock(lock_path); release_install_lock(download_lock); MessageDialog dlg(this->mainframe, _L("Could not prepare the update."), _L("Update"), wxOK | wxICON_ERROR); dlg.ShowModal(); - return; + return false; } // Close the app before the helper starts: the running binary cannot be replaced. @@ -7138,18 +7154,20 @@ void GUI_App::start_in_app_update() if (!mainframe || !mainframe->Close(false)) { release_install_lock(lock_path); release_install_lock(download_lock); - remove_handoff(); - return; + remove_handoff(updater_install_job); + return false; } // The helper outlives this process and must not keep the log folder as its working directory. - if (!launch_updater_helper(helper, {})) { + if (!launch_updater_helper(helper, {}, updater_install_job)) { release_install_lock(lock_path); release_install_lock(download_lock); - remove_handoff(); + remove_handoff(updater_install_job); MessageDialog dlg(nullptr, _L("Could not start the updater."), _L("Update"), wxOK | wxICON_ERROR); dlg.ShowModal(); + return false; } + return true; } bool GUI_App::prefetch_update() @@ -7176,15 +7194,15 @@ bool GUI_App::prefetch_update() return false; } - if (!write_handoff(make_update_handoff(m_update_candidate))) { + if (!write_handoff(make_update_handoff(m_update_candidate), updater_prefetch_job)) { BOOST_LOG_TRIVIAL(warning) << "Not prefetching the update: could not write the handoff"; return false; } m_prefetching_artifact = artifact; - if (!launch_updater_helper(helper, {L"--silent"})) { + if (!launch_updater_helper(helper, {L"--silent"}, updater_prefetch_job)) { m_prefetching_artifact.clear(); - remove_handoff(); + remove_handoff(updater_prefetch_job); BOOST_LOG_TRIVIAL(warning) << "Could not start the background download of " << m_update_candidate.asset.name; return false; } @@ -7197,10 +7215,6 @@ void GUI_App::show_update_dialog() if (!m_update_candidate.available) return; - // The notification has done its job: the dialog answers for the same candidate. - if (NotificationManager* notifications = notification_manager()) - notifications->close_notification_of_type(NotificationType::AppUpdateReady); - // 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; @@ -7223,11 +7237,15 @@ void GUI_App::show_update_dialog() case wxID_YES: // Store builds get updates from the Microsoft Store and Flatpak builds from // Flathub. Download-only installs open the asset itself. - if (can_install_in_app(m_update_candidate, current_install_flavour())) - start_in_app_update(); - else + if (can_install_in_app(m_update_candidate, current_install_flavour())) { + // A refused install leaves the candidate, its notification and its poll in place: + // the release is still on offer, and the artifact may still finish downloading. + if (!start_in_app_update()) + return; + } else { open_update_page(m_update_candidate); - // The page replaces the install: nothing may remain armed for this candidate. + } + // The page or the helper answers for this candidate: nothing may remain armed for it. m_update_candidate = UpdateCandidate(); break; case wxID_NO: @@ -7236,13 +7254,16 @@ void GUI_App::show_update_dialog() break; } - // The dialog answered for this candidate: the poll has nothing left to watch. The - // notified identity is kept, so dismissing the dialog stays quiet for this session. + // The dialog answered for this candidate: the notification and the poll have nothing + // left to watch. The notified identity is kept, so dismissing the dialog stays quiet + // for this session. + if (NotificationManager* notifications = notification_manager()) + notifications->close_notification_of_type(NotificationType::AppUpdateReady); if (m_update_ready_timer) m_update_ready_timer->Stop(); } -void GUI_App::notify_update_ready() +void GUI_App::notify_update_ready(bool verified) { if (m_update_notified_identity == m_update_candidate.identity()) return; @@ -7251,10 +7272,16 @@ void GUI_App::notify_update_ready() return; // Warning is the only level that does not fade: Important disappears after 20 s. + // A flavour that cannot install in place is offered the same way: its dialog opens the + // Store, Flathub or the asset, and is the only place Skip this Version exists. + const bool installable = verified && can_install_in_app(m_update_candidate, current_install_flavour()); + const std::string text = installable + ? format(_u8L("OrcaSlicer %1% is ready to install."), m_update_candidate.version_label) + : format(_u8L("OrcaSlicer %1% is available."), m_update_candidate.version_label); notifications->push_notification(NotificationType::AppUpdateReady, NotificationManager::NotificationLevel::WarningNotificationLevel, - format(_u8L("OrcaSlicer %1% is ready to install."), m_update_candidate.version_label), - _u8L("Install update"), + text, + installable ? _u8L("Install update") : _u8L("View update"), [](wxEvtHandler*) { wxGetApp().CallAfter([] { wxGetApp().show_update_dialog(); }); return true; @@ -7340,7 +7367,12 @@ void GUI_App::finish_pending_update() // not, and retrying it on every start would warn forever. bool settled = true; - if (!pending.backup.empty()) { + if (!pending.backup.empty() && !is_moved_aside_tree(pending.backup, pending.target)) { + // A record naming anything but the tree a helper moved aside is not acted on: + // the deletion below would run on a path this install never wrote. + BOOST_LOG_TRIVIAL(warning) << "Ignoring a pending update record with an unexpected backup " << pending.backup; + settled = false; + } else if (!pending.backup.empty()) { boost::system::error_code exists_ec; const bool target_exists = !pending.target.empty() && fs::exists(fs::path(pending.target), exists_ec); const bool backup_exists = fs::exists(fs::path(pending.backup), exists_ec); @@ -9703,7 +9735,9 @@ void GUI_App::open_preferences(PreferencesTab tab, const std::string& highlight_ m_update_candidate = UpdateCandidate(); if (!old_asset.empty()) drop_cached_update(old_asset); - check_new_version_sf(true, 1); + // Deferred past the GUI rebuild: the check's answer opens a modal dialog, which + // must not land while recreate_GUI() is still swapping the main frame. + CallAfter([] { wxGetApp().check_new_version_sf(true, 1); }); } need_recreate_gui = dlg.recreate_GUI(); pending_language = dlg.pending_language(); diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index 742da8e931..b93f0ab7d4 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -620,13 +620,16 @@ public: void check_new_version_sf(bool show_tips = false, int by_user = 0); // Hands the resolved update to the helper: writes the handoff, extracts and spawns the - // helper, and closes the app. Falls back to the release page when that is not possible. - void start_in_app_update(); + // helper, and closes the app. False when the install did not start, so the caller keeps + // the candidate on offer. + bool start_in_app_update(); // Offers the candidate: install in place or open the release page. Called by a manual // check and by the ready notification's action, never by the automatic check. void show_update_dialog(); - // Pushes the persistent "ready to install" notification for the current candidate. - void notify_update_ready(); + // Pushes the persistent notification for the current candidate: "ready to install" once + // its artifact is verified and this flavour installs in place, "available" otherwise. Its + // action opens the update dialog either way, where Skip is offered. + void notify_update_ready(bool verified = true); // Starts the download the automatic check hands to the helper, without a dialog or a // lock; the notification follows once the artifact is verified. False when no helper was // started, so there is nothing to poll for. diff --git a/src/slic3r/UpdateHelper/HttpDownloader.cpp b/src/slic3r/UpdateHelper/HttpDownloader.cpp index e21137322f..7a8cdebdc2 100644 --- a/src/slic3r/UpdateHelper/HttpDownloader.cpp +++ b/src/slic3r/UpdateHelper/HttpDownloader.cpp @@ -59,6 +59,8 @@ struct TransferCtx bool write_failed = false; const std::atomic* cancel = nullptr; bool saw_cancel = false; + bool too_large = false; + curl_off_t max_bytes = 0; const HttpDownloader::ProgressFn* progress = nullptr; curl_off_t last_reported = -1; curl_off_t total = 0; @@ -100,6 +102,11 @@ size_t write_cb(char* ptr, size_t size, size_t nmemb, void* userdata) } } } + if (ctx.max_bytes > 0 && ctx.done + static_cast(bytes) > ctx.max_bytes) { + // Never let a redirected body run past the size the release announced. + ctx.too_large = true; + return 0; + } const size_t written = bytes > 0 ? std::fwrite(ptr, 1, bytes, ctx.file) : 0; if (written != bytes) { ctx.write_failed = true; @@ -165,7 +172,8 @@ std::string HttpDownloader::user_agent() DownloadResult HttpDownloader::download(const std::string& url, const std::string& part_path, const ProgressFn& progress, - const std::atomic& cancel) const + const std::atomic& cancel, + int64_t max_bytes) const { DownloadResult out; @@ -221,6 +229,7 @@ DownloadResult HttpDownloader::download(const std::string& url, ctx.resume = resume; ctx.done = resume; ctx.cancel = &cancel; + ctx.max_bytes = static_cast(std::max(max_bytes, 0)); ctx.progress = &progress; char error_buffer[CURL_ERROR_SIZE] = { 0 }; @@ -282,6 +291,10 @@ DownloadResult HttpDownloader::download(const std::string& url, out.cancelled = true; return out; } + if (ctx.too_large) { + out.error = "The download is larger than the release says."; + return out; + } if (ctx.write_failed) { out.error = "Could not write the download to disk."; return out; diff --git a/src/slic3r/UpdateHelper/HttpDownloader.hpp b/src/slic3r/UpdateHelper/HttpDownloader.hpp index 2c605f0b7d..2ffc90e86a 100644 --- a/src/slic3r/UpdateHelper/HttpDownloader.hpp +++ b/src/slic3r/UpdateHelper/HttpDownloader.hpp @@ -33,10 +33,13 @@ public: // Creates the parent directory of `part_path` when it is missing and resumes // from the current .part size. `cancel` is polled from libcurl's progress // callback; setting it aborts the transfer and leaves the .part in place. + // `max_bytes` stops a body larger than the release announced from filling the disk; + // zero means no ceiling. DownloadResult download(const std::string& url, const std::string& part_path, const ProgressFn& progress, - const std::atomic& cancel) const; + const std::atomic& cancel, + int64_t max_bytes = 0) const; static std::string user_agent(); }; diff --git a/src/slic3r/UpdateHelper/InstallApply.hpp b/src/slic3r/UpdateHelper/InstallApply.hpp index c5089aafdb..2566862e5f 100644 --- a/src/slic3r/UpdateHelper/InstallApply.hpp +++ b/src/slic3r/UpdateHelper/InstallApply.hpp @@ -32,6 +32,10 @@ struct ProgressSink { std::function report; std::function cancelled; + // Called once the new build is in place and recorded, immediately before it is + // started: the helper releases the install lock here so the new build's own startup + // can settle the install records instead of finding the lock still held. + std::function release_lock; void say(Stage stage, int percent, const std::string& message) const { diff --git a/src/slic3r/UpdateHelper/UpdateHelperFrame.cpp b/src/slic3r/UpdateHelper/UpdateHelperFrame.cpp index f4b7dbbd82..62ec553afa 100644 --- a/src/slic3r/UpdateHelper/UpdateHelperFrame.cpp +++ b/src/slic3r/UpdateHelper/UpdateHelperFrame.cpp @@ -68,6 +68,8 @@ constexpr int kParentTimeoutSeconds = 300; constexpr int kLockRetryMs = 250; constexpr int kLockTimeoutMs = 10000; constexpr int64_t kShaBufferSize = 64 * 1024; +// The log is appended across runs and only rotated past this size. +constexpr uintmax_t kLogRotateBytes = 512 * 1024; std::string timestamp() { @@ -235,9 +237,15 @@ void LogFile::write(const std::string& message) if (!parent.empty()) fs::create_directories(parent, ec); - // Truncated on the first write of a run: the log describes the run in progress, so it - // never accumulates one copy of itself per update. - boost::nowide::ofstream out(path.string(), (m_started ? std::ios::app : std::ios::trunc) | std::ios::binary); + // Appended across runs, so a prefetch helper starting after a failed install does not + // wipe the trail that install's dialog points at. Rotated only once it is large. + bool truncate = false; + if (!m_started) { + boost::system::error_code size_ec; + const auto size = fs::file_size(path, size_ec); + truncate = !size_ec && size > kLogRotateBytes; + } + boost::nowide::ofstream out(path.string(), (truncate ? std::ios::trunc : std::ios::app) | std::ios::binary); if (!out) return; m_started = true; @@ -323,7 +331,9 @@ void UpdateHelperFrame::on_cancel(wxCommandEvent& /*event*/) void UpdateHelperFrame::on_close(wxCloseEvent& event) { if (m_worker_done) { - event.Skip(); + // finish() already queued the completion that ends the main loop. Destroying the + // frame here would leave that queued work writing to freed widgets. + event.Veto(); return; } if (m_stage == Stage::Installing || m_stage == Stage::Launching) { @@ -370,8 +380,12 @@ void UpdateHelperFrame::finish(int code, const wxString& message, bool alert) // has no window to say that in, so it leaves the message for the next start. const bool relaunch = code != 0 && m_parent_gone && !silent(); wxTheApp->CallAfter([this, message, alert, relaunch, code]() { - if (relaunch && !relaunch_app(m_handoff)) - m_log.write("could not start the application again"); + if (relaunch) { + // The new start settles the install records; it must not find this run's lock. + Slic3r::release_install_lock(m_handoff.lock_path); + if (!relaunch_app(m_handoff)) + m_log.write("could not start the application again"); + } if (!message.empty()) { m_status->SetLabel(message); Layout(); @@ -562,7 +576,7 @@ bool UpdateHelperFrame::fetch_artifact(const fs::path& download_dir, const fs::p message += " of " + human_bytes(total); post(Stage::Downloading, percent, message); }, - m_cancel_requested); + m_cancel_requested, m_handoff.size); if (result.cancelled) { m_log.write("download cancelled at " + std::to_string(result.done) + " bytes"); @@ -730,10 +744,11 @@ void UpdateHelperFrame::run() sink.report = [this](Stage stage, int percent, const std::string& message) { if (stage == Stage::Failed) { // The install stopped without failing: the Windows installer outlived its - // timeout and is still writing the tree. Nothing is recorded and nothing is - // started, so the run ends 0 with the message to the user. - m_unfinished_install = message; - m_log.write("install unfinished: " + message); + // timeout and is still writing the tree, or the new build is in place but + // could not be started. The run ends 0 with the message to the user instead + // of reporting a failed update. + m_install_notice = message; + m_log.write("install incomplete: " + message); post(stage, percent, message); return; } @@ -741,12 +756,25 @@ void UpdateHelperFrame::run() post(stage, percent, message); }; sink.cancelled = [this]() { return m_cancel_requested.load(); }; + // The installer has run by the time this is called: drop the handle on the file and + // the install lock, so the new build's cleanup can delete the download and settle + // the records. + sink.release_lock = [this, &hold] { + hold.close(); + Slic3r::release_install_lock(m_handoff.lock_path); + }; std::string install_error; if (!apply_update(m_handoff, artifact.string(), sink, install_error)) { - if (!m_unfinished_install.empty()) { - m_log.write("leaving the running installer to finish the update"); - finish(0, wxString::FromUTF8(m_unfinished_install), !silent()); + if (!m_install_notice.empty()) { + m_log.write("leaving the update in place to report: " + m_install_notice); + finish(0, wxString::FromUTF8(m_install_notice), !silent()); + return; + } + // A cancel that reached the install before the swap is not a failure. + if (m_cancel_requested.load()) { + m_log.write("install cancelled before it started"); + finish(2, "Update cancelled.", false); return; } m_log.write("install failed: " + install_error); diff --git a/src/slic3r/UpdateHelper/UpdateHelperFrame.hpp b/src/slic3r/UpdateHelper/UpdateHelperFrame.hpp index 01a03079e1..350f70f667 100644 --- a/src/slic3r/UpdateHelper/UpdateHelperFrame.hpp +++ b/src/slic3r/UpdateHelper/UpdateHelperFrame.hpp @@ -29,8 +29,8 @@ namespace Updater { // Starts the application again after an update that did not install. False when it could not be started. bool relaunch_app(const UpdateHandoff& handoff); -// Writes timestamped lines to handoff.log_path, starting a new log for each run. -// Safe to call from any thread. +// Writes timestamped lines to handoff.log_path, appended across runs and rotated once +// it grows past a few hundred kilobytes. Safe to call from any thread. class LogFile { public: @@ -108,8 +108,8 @@ private: // Worker thread only. Set once the parent is gone, so the application can be started again. bool m_parent_gone = false; // Worker thread only. Set by an install that stopped without failing: the Windows - // installer outlived its timeout and is still writing the tree. - std::string m_unfinished_install; + // installer outlived its timeout, or the new build is in place but did not start. + std::string m_install_notice; std::thread m_worker; }; diff --git a/src/slic3r/UpdateHelper/apply_macos.cpp b/src/slic3r/UpdateHelper/apply_macos.cpp index d65697a600..233d914fee 100644 --- a/src/slic3r/UpdateHelper/apply_macos.cpp +++ b/src/slic3r/UpdateHelper/apply_macos.cpp @@ -518,9 +518,16 @@ bool apply_macos_install(const UpdateHandoff& handoff, const std::string& artifa return false; } - if (launch && !spawn_unwaited({"/usr/bin/open", "-n", bundle}, error)) { - error = rollback_failure(error); - return false; + if (launch) { + if (sink.release_lock) + sink.release_lock(); + if (!spawn_unwaited({ "/usr/bin/open", "-n", bundle }, error)) { + // The bundle is in place and recorded, so the update succeeded; only starting it + // failed. Rolling back here would undo a good install for a transient + // LaunchServices error. + sink.say(Stage::Failed, 100, "OrcaSlicer was updated but could not be started. Start it again."); + return false; + } } // Success: the previous bundle and the pending record stay behind on purpose; the diff --git a/src/slic3r/UpdateHelper/apply_windows.cpp b/src/slic3r/UpdateHelper/apply_windows.cpp index c4c5819496..27dfab77a7 100644 --- a/src/slic3r/UpdateHelper/apply_windows.cpp +++ b/src/slic3r/UpdateHelper/apply_windows.cpp @@ -356,7 +356,15 @@ InstallerResult wait_for_installer(HANDLE process, std::string& error) return InstallerResult::Failed; } if (!got_exit || exit_code != 0) { - error = "The installer reported a failure (exit code " + std::to_string(static_cast(got_exit ? exit_code : 1)) + ")."; + if (got_exit && exit_code == 2) { + // The installer's own code for "nothing was written": the tree was in use or the + // stage could not be created. Its silent message never reaches the user. + error = "The installer made no changes: another OrcaSlicer window kept the folder in use, " + "or the new files could not be written."; + } else { + error = "The installer reported a failure (exit code " + + std::to_string(static_cast(got_exit ? exit_code : 1)) + ")."; + } return InstallerResult::Failed; } return InstallerResult::Done; @@ -653,11 +661,16 @@ bool apply_windows_install(const UpdateHandoff& handoff, const std::string& arti BOOST_LOG_TRIVIAL(warning) << "Could not record the installed build " << handoff.version; const std::string exe_path = handoff.exe_path.empty() ? install_root + "\\orca-slicer.exe" : handoff.exe_path; - if (launch && !launch_detached(exe_path, error)) { - remove_path_quietly(updater_install_record_path()); - remove_pending_install(); - error += " The installer finished, but the new version did not start."; - return false; + if (launch) { + if (sink.release_lock) + sink.release_lock(); + if (!launch_detached(exe_path, error)) { + // The tree is in place and recorded; only starting it failed. Keep both records + // so the build the user starts knows what it is, and report the start, not the + // update, as what went wrong. + sink.say(Stage::Failed, 100, "OrcaSlicer was updated but could not be started. Start it again."); + return false; + } } return true; } diff --git a/src/slic3r/UpdateHelper/main.cpp b/src/slic3r/UpdateHelper/main.cpp index f0d7e1a0de..fe3ec18dc8 100644 --- a/src/slic3r/UpdateHelper/main.cpp +++ b/src/slic3r/UpdateHelper/main.cpp @@ -152,9 +152,9 @@ bool UpdateHelperApp::OnInit() m_lock_path = handoff.lock_path.empty() ? Slic3r::updater_lock_path() : handoff.lock_path; handoff.lock_path = m_lock_path; - // A handoff is good for one run only: delete it before anything else so a - // stale file can never replay this update. - Slic3r::remove_handoff(); + // A handoff is good for one run only: delete this run's file before anything else so a + // stale file can never replay this update. Only this job's file is removed, so a helper + // started for the other job still finds its own. { boost::system::error_code ec; fs::remove(path, ec); diff --git a/tests/libslic3r/update_channel_tests.cpp b/tests/libslic3r/update_channel_tests.cpp index f245b04931..25ab47f20f 100644 --- a/tests/libslic3r/update_channel_tests.cpp +++ b/tests/libslic3r/update_channel_tests.cpp @@ -773,6 +773,18 @@ TEST_CASE("A stable release that is not newer is not offered even with a stale i CHECK(candidate.version == "2.5.0"); } +TEST_CASE("A recorded digest of a newer build does not hide it after a downgrade", "[UpdateChannel]") +{ + // An in-app install of 2.5.0 recorded its digest, then a 2.4.0 build was run from the same + // path. The digest names the installed artifact, not proof that the running build is it. + const UpdateCandidate candidate = resolve_update(stable_releases_json(), UpdateChannel::Stable, + "sha256:2222", "stable", "2.4.0", "", + InstallFlavour::WindowsInstaller, "x86_64"); + + CHECK(candidate.available); + CHECK(candidate.version == "2.5.0"); +} + TEST_CASE("A release that is not newer is not offered when its flavour has no asset either", "[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 a3f8fc8da0..daecc33b01 100644 --- a/tests/libslic3r/update_handoff_tests.cpp +++ b/tests/libslic3r/update_handoff_tests.cpp @@ -574,6 +574,31 @@ TEST_CASE("The handoff round-trips through a cache directory with non-ASCII char clear_updater_cache_dir(); } +TEST_CASE("A prefetch and an install job do not overwrite or consume each other", "[UpdateHandoff]") +{ + ScopedTemporaryDir dir; + set_updater_cache_dir(dir.path().string()); + set_updater_install_root("/opt/OrcaSlicer"); + + UpdateHandoff prefetch; + prefetch.version = "from the prefetch"; + UpdateHandoff install; + install.version = "from the install"; + CHECK(write_handoff(prefetch, "prefetch")); + CHECK(write_handoff(install, "install")); + CHECK(updater_handoff_path("prefetch") != updater_handoff_path("install")); + + // Each helper removes only its own file, so the other job stays readable. + remove_handoff("prefetch"); + UpdateHandoff missing; + CHECK_FALSE(read_handoff(missing, "prefetch")); + UpdateHandoff read; + CHECK(read_handoff(read, "install")); + CHECK(read.version == "from the install"); + + clear_updater_cache_dir(); +} + TEST_CASE("An install record round-trips with the install it describes", "[UpdateHandoff]") { InstallRecord written;