diff --git a/app/shell/installer.nsi b/app/shell/installer.nsi index ae74dfc..c51a2f6 100644 --- a/app/shell/installer.nsi +++ b/app/shell/installer.nsi @@ -1,5 +1,6 @@ ; The Jarvis installer (admin.spec.md, "Installer"). Built on Linux by installer.sh with makensis: -; makensis -DVERSION=0.1.0 -DSRC= -DOUT= -DICON= -DWEBVIEW2= installer.nsi +; makensis -DVERSION=0.1.0 -DSRC= -DOUT= -DICON= -DWEBVIEW2= +; -DUNINSTALL_LIST= installer.nsi ; Program Files, one administrator prompt; the data folder is chosen by the app's first-run wizard ; and never touched here. /S installs silently (the app's updates: /S /RUN starts the app afterwards). @@ -11,7 +12,9 @@ SetCompressor /SOLID lzma !include "FileFunc.nsh" !define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\JarvisBot" -!define WEBVIEW2_KEY "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" +!ifndef WEBVIEW2_KEY ; a test build points it elsewhere to act as a PC without the runtime + !define WEBVIEW2_KEY "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" +!endif Name "Jarvis" OutFile "${OUT}" @@ -95,6 +98,12 @@ FunctionEnd ${Loop} !macroend +; The installer's lock: Jarvis does not start while it is held (app/src/setup_lock.rs); taken +; before waiting for a running Jarvis, held until the installer ends. +!macro TakeLock + System::Call 'kernel32::CreateMutexW(p 0, i 1, w "Global\JarvisBotSetup") p .r9' +!macroend + Function .onInit ${IfNot} ${RunningX64} MessageBox MB_ICONSTOP "Jarvis는 64비트 Windows 10/11에서만 실행됩니다." @@ -103,15 +112,61 @@ Function .onInit SetRegView 64 ; Shortcuts for every user of the PC, like the Program Files install itself. SetShellVarContext all + !insertmacro TakeLock !insertmacro WaitClosed "" FunctionEnd Function un.onInit SetRegView 64 SetShellVarContext all + !insertmacro TakeLock !insertmacro WaitClosed "un." FunctionEnd +; The window needs the WebView2 runtime (Windows 11 has it; an older Windows 10 may not). Checked +; before any file is copied: without it nothing is installed (and /RUN starts nothing). +Function WebView2Present + ReadRegStr $0 HKLM "${WEBVIEW2_KEY}" "pv" + ReadRegStr $1 HKCU "${WEBVIEW2_KEY}" "pv" + StrCpy $2 0 + ${If} $0 != "" + ${AndIf} $0 != "0.0.0.0" + StrCpy $2 1 + ${EndIf} + ${If} $1 != "" + ${AndIf} $1 != "0.0.0.0" + StrCpy $2 1 + ${EndIf} + Push $2 +FunctionEnd + +Function EnsureWebView2 + Call WebView2Present + Pop $2 + ${If} $2 == 1 + Return + ${EndIf} + SetOutPath "$PLUGINSDIR" + File "/oname=webview2.exe" "${WEBVIEW2}" + ${Do} + DetailPrint "WebView2 런타임 설치" + ExecWait '"$PLUGINSDIR\webview2.exe" /silent /install' $0 + Call WebView2Present + Pop $2 + ${If} $2 == 1 + Return + ${EndIf} + DetailPrint "WebView2 런타임을 설치하지 못했습니다 (결과 $0)" + ${If} ${Silent} + SetErrorLevel 3 + Abort "WebView2 런타임을 설치하지 못했습니다." + ${EndIf} + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Jarvis 창에 필요한 WebView2 런타임을 설치하지 못했습니다. 인터넷 연결을 확인하고 다시 시도해 주세요." IDRETRY +3 + SetErrorLevel 3 + Abort "WebView2 런타임이 없어 설치하지 않았습니다." + ${Loop} +FunctionEnd + ; Started from this elevated installer the app would run as administrator; Explorer starts it as ; the signed-in user. Function RunAsUser @@ -120,6 +175,9 @@ FunctionEnd Section "Jarvis (필수)" SecMain SectionIn RO + ; Again right before changing anything: a Jarvis started since the first look closes first. + !insertmacro WaitClosed "" + Call EnsureWebView2 SetOutPath "$INSTDIR" File "${SRC}/jarvis.exe" File "${SRC}/WebView2Loader.dll" @@ -138,21 +196,6 @@ Section "Jarvis (필수)" SecMain WriteRegDWORD HKLM "${UNINST_KEY}" "NoRepair" 1 ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2 WriteRegDWORD HKLM "${UNINST_KEY}" "EstimatedSize" $0 - ; The window needs the WebView2 runtime (Windows 11 has it; an older Windows 10 may not). - ReadRegStr $0 HKLM "${WEBVIEW2_KEY}" "pv" - ReadRegStr $1 HKCU "${WEBVIEW2_KEY}" "pv" - ${If} $0 == "" - ${OrIf} $0 == "0.0.0.0" - ${If} $1 == "" - ${OrIf} $1 == "0.0.0.0" - DetailPrint "WebView2 런타임 설치" - SetOutPath "$PLUGINSDIR" - File "/oname=webview2.exe" "${WEBVIEW2}" - ExecWait '"$PLUGINSDIR\webview2.exe" /silent /install' $0 - DetailPrint "WebView2 설치 결과: $0" - SetOutPath "$INSTDIR" - ${EndIf} - ${EndIf} ; Silent updates (/S /RUN) start the app again when done. ${GetParameters} $0 ClearErrors @@ -193,15 +236,31 @@ LangString DESC_Driver ${LANG_KOREAN} "봇용 크롬창을 실제 모니터에 !insertmacro MUI_FUNCTION_DESCRIPTION_END Section "Uninstall" - ; The virtual monitor's driver goes with the app when this app installed it (the elevated half - ; refuses another program's copy and does nothing when there is none). - ExecWait '"$INSTDIR\jarvis.exe" --display-driver uninstall --result "$TEMP\jarvis-vdd-uninstall.txt"' + !insertmacro WaitClosed "un." + ; The virtual monitor's driver goes with the app when this app installed it (code 0). Code 2: + ; nothing of this app's to remove (none, or another program's copy). Anything else: it stays, + ; so the uninstall stops here and keeps the app, which can remove it or try again. + ExecWait '"$INSTDIR\jarvis.exe" --display-driver uninstall --result "$TEMP\jarvis-vdd-uninstall.txt"' $0 + ${If} $0 != 0 + ${AndIf} $0 != 2 + StrCpy $2 "" + FileOpen $1 "$TEMP\jarvis-vdd-uninstall.txt" r + FileRead $1 $2 + FileClose $1 + Delete "$TEMP\jarvis-vdd-uninstall.txt" + DetailPrint "가상 모니터 드라이버를 지우지 못했습니다 ($0): $2" + ${IfNot} ${Silent} + MessageBox MB_ICONSTOP "가상 모니터 드라이버를 지우지 못해 제거를 멈췄습니다. Jarvis의 기능 화면에서 드라이버를 제거한 뒤 다시 시도해 주세요.$\r$\n$2" + ${EndIf} + SetErrorLevel 4 + Abort "가상 모니터 드라이버를 지우지 못했습니다." + ${EndIf} Delete "$TEMP\jarvis-vdd-uninstall.txt" - ; Only what the installer put there: a folder the person chose may hold other things. + ; Only the files the installer put there (the list is made from the package at build time): a + ; folder the person chose may hold other things; folders go only when empty. Delete "$INSTDIR\jarvis.exe" Delete "$INSTDIR\WebView2Loader.dll" - RMDir /r "$INSTDIR\python-src" - RMDir /r "$INSTDIR\display-driver" + !include "${UNINSTALL_LIST}" Delete "$INSTDIR\uninstall.exe" RMDir "$INSTDIR" Delete "$SMPROGRAMS\Jarvis.lnk" diff --git a/app/shell/installer.sh b/app/shell/installer.sh index c58c4f6..fd07c35 100755 --- a/app/shell/installer.sh +++ b/app/shell/installer.sh @@ -11,8 +11,13 @@ sh "$here/package.sh" "$out" >/dev/null # The WebView2 runtime's bootstrapper (Microsoft, about 2 MB), run only on a PC without the runtime. wv2="$target/MicrosoftEdgeWebview2Setup.exe" [ -s "$wv2" ] || curl -fsSL -o "$wv2" "https://go.microsoft.com/fwlink/p/?LinkId=2124703" +# What the uninstaller removes: exactly the files installed under python-src and display-driver, +# then their folders, deepest first, each only when empty. +list="$target/uninstall-list.nsh" +(cd "$out/Jarvis" && find python-src display-driver -type f | sort | sed 's|/|\\|g; s|^| Delete "$INSTDIR\\|; s|$|"|' + cd "$out/Jarvis" && find python-src display-driver -type d | sort -r | sed 's|/|\\|g; s|^| RMDir "$INSTDIR\\|; s|$|"|') > "$list" setup="$out/Jarvis-Setup-$version.exe" makensis -V2 -DVERSION="$version" -DSRC="$out/Jarvis" -DOUT="$setup" -DICON="$here/icons/icon.ico" \ - -DWEBVIEW2="$wv2" "$here/installer.nsi" + -DWEBVIEW2="$wv2" -DUNINSTALL_LIST="$list" ${NSIS_EXTRA:-} "$here/installer.nsi" (cd "$out" && sha256sum "Jarvis-Setup-$version.exe" > "Jarvis-Setup-$version.exe.sha256") echo "$setup" diff --git a/app/shell/src/main.rs b/app/shell/src/main.rs index 51447da..af663f6 100644 --- a/app/shell/src/main.rs +++ b/app/shell/src/main.rs @@ -41,6 +41,11 @@ fn main() { if let Some(code) = jarvis_app::vdisplay::elevated_main(&std::env::args().collect::>()) { std::process::exit(code); } + // Not while an installer installs, updates or removes Jarvis (admin.spec.md, "Installer"). + if jarvis_app::setup_lock::held() { + jarvis_app::setup_lock::tell(); + std::process::exit(3); + } let location = arg("--location").map(PathBuf::from).or_else(jarvis_app::datadir::default_location_file) .expect("no location file path: pass --location"); // Log files go to the data folder once there is one; until then memory only. diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 2a93b20..caacea1 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -302,7 +302,9 @@ the browser runs headless with a note. devices, whatever their class (a device whose driver was declined has none). The settings: one monitor, one mode (1280x720 at 30 Hz), no custom EDID. When another program's copy of the same driver is installed (its `VDDPATH` is not ours) the app refuses to install or - remove and never touches its monitors. Uninstall removes the device, then the driver package (one + remove and never touches its monitors; the elevated half asked to remove a driver that is not + ours (another program's, or none) does nothing and exits with code 2, which the app and the + uninstaller take as nothing to remove. Uninstall removes the device, then the driver package (one not in the driver store counts as gone), and only then the registry key, which makes it ours, and the settings folder; when a device or the package stays, it fails with the reason and keeps the registry key, so a retry is still allowed. @@ -576,14 +578,23 @@ come with the first-run wizard into the data folder, which the installer never t asks the SignPath question once; a failure says it can be installed later from the features screen). Shortcuts are for every user of the PC. - The WebView2 runtime is installed with Microsoft's bootstrapper (inside the installer) only when - the PC has none. -- Before installing or removing, the installer waits for `jarvis.exe` to close: it asks with a - retry, or silently waits up to 60 s (an update closes the app itself), then gives up. + the PC has none, before any file is copied. When it is still missing afterwards the installer + asks to retry or cancel; silently it stops with exit code 3, nothing installed and nothing + started. +- While it installs, updates or removes, the installer holds the named mutex + `Global\JarvisBotSetup` (`setup_lock.rs`); `jarvis.exe` started meanwhile says so in a message + box and exits (code 3) before any window or service. Before copying or removing, the installer + also waits for `jarvis.exe` to close: it asks with a retry, or silently waits up to 60 s (an + update closes the app itself), then gives up. - `/S` installs silently with the default components; `/S /RUN` starts the app again afterwards (the app's updates). The uninstall entry has the version, size and a quiet uninstall string. -- Uninstall: the driver goes too when this app installed it (the elevated half refuses another - program's copy), then only what the installer put there (a folder the person chose may hold - other things), the shortcuts and the registry keys. The data folder stays. +- Uninstall: the driver goes first when this app installed it (`--display-driver uninstall`: + 0 removed, 2 nothing of ours to remove; the elevated half refuses another program's copy). Any + other result stops the uninstall with everything kept, so it can be run again (silently exit + code 4). Then only what the installer put there goes: `installer.sh` lists every file of + `python-src/` and `display-driver/` for the uninstaller (`uninstall-list.nsh`) and folders are + removed only when empty, so a folder the person chose keeps its other things. Then the + shortcuts and the registry keys. The data folder stays. ## Tests @@ -656,5 +667,10 @@ entries, non-ASCII paths, the person's lists first, staying on until the game en detection off) and its settings. A removal forgets the driver only when no device is left and the package is gone or was not in the store; a failed install forgets it only under the same rule (and never when it was ours before), reporting both reasons otherwise; a leftover offers removal; driver tasks refused while the services start, and a start (and a -second task) refused while one runs, also after it failed. On Linux the same window test runs on an X display (one window at the given place and +second task) refused while one runs, also after it failed; removing a driver that is not ours says +there is nothing to remove. The installer (by hand on a Windows VM): installing into a folder that +holds other files and uninstalling keeps them; a driver removal that fails stops the uninstall with +the files and entry kept, and nothing to remove lets it finish; with no WebView2 and its installer +failing nothing is installed or started; with the lock held the app shows its message and exits +after OK, and starts normally once released. On Linux the same window test runs on an X display (one window at the given place and size, the bot's tab in it). diff --git a/app/src/lib.rs b/app/src/lib.rs index bcdab14..a89515a 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -29,6 +29,7 @@ pub mod secrets; pub mod services; pub mod settings; pub mod settings_edit; +pub mod setup_lock; pub mod speakers; pub mod strata; pub mod system; diff --git a/app/src/setup_lock.rs b/app/src/setup_lock.rs new file mode 100644 index 0000000..e1e1473 --- /dev/null +++ b/app/src/setup_lock.rs @@ -0,0 +1,41 @@ +//! The installer's lock (admin.spec.md, "Installer"): while Jarvis is installed, updated or +//! removed, the installer holds the named mutex `Global\JarvisBotSetup`, and the app does not +//! start meanwhile (it would hold files being replaced, or start services on a driver being +//! removed). + +pub const MUTEX: &str = "Global\\JarvisBotSetup"; + +/// Whether an installer holds the lock (also when this user may not open it: it exists). +#[cfg(windows)] +pub fn held() -> bool { + use windows_sys::Win32::Foundation::{CloseHandle, GetLastError, ERROR_ACCESS_DENIED}; + use windows_sys::Win32::System::Threading::{OpenMutexW, SYNCHRONIZATION_SYNCHRONIZE}; + let name: Vec = MUTEX.encode_utf16().chain(Some(0)).collect(); + // SAFETY: opening a named object by a NUL-terminated name; the handle is closed at once. + unsafe { + let h = OpenMutexW(SYNCHRONIZATION_SYNCHRONIZE, 0, name.as_ptr()); + if !h.is_null() { + CloseHandle(h); + return true; + } + GetLastError() == ERROR_ACCESS_DENIED + } +} + +#[cfg(not(windows))] +pub fn held() -> bool { + false +} + +/// Say so in a message box (the app has no window yet). +#[cfg(windows)] +pub fn tell() { + use windows_sys::Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_ICONINFORMATION, MB_OK}; + let text: Vec = "Jarvis를 설치하거나 제거하는 중입니다. 끝난 뒤 다시 실행해 주세요.".encode_utf16().chain(Some(0)).collect(); + let title: Vec = "Jarvis".encode_utf16().chain(Some(0)).collect(); + // SAFETY: NUL-terminated strings; no owner window. + unsafe { MessageBoxW(std::ptr::null_mut(), text.as_ptr(), title.as_ptr(), MB_OK | MB_ICONINFORMATION) }; +} + +#[cfg(not(windows))] +pub fn tell() {} diff --git a/app/src/vdisplay.rs b/app/src/vdisplay.rs index d788944..8694a99 100644 --- a/app/src/vdisplay.rs +++ b/app/src/vdisplay.rs @@ -124,12 +124,22 @@ pub async fn run_elevated(_action: &str) -> Result<(), String> { Err("가상 모니터는 Windows에서만 씁니다".into()) } +/// The elevated half's exit code when removing finds no driver of this app's (none, or another +/// program's copy): the uninstaller goes on. 0 is done, 1 failed (the uninstaller stops). +pub const NOTHING_TO_REMOVE: i32 = 2; + /// `jarvis.exe --display-driver install|uninstall --result FILE`: the elevated half of /// `run_elevated`; the outcome (empty, or why it failed) goes to FILE. `None` without the option. pub fn elevated_main(args: &[String]) -> Option { let i = args.iter().position(|a| a == "--display-driver")?; let action = args.get(i + 1).map(String::as_str).unwrap_or(""); let result = args.iter().position(|a| a == "--result").and_then(|j| args.get(j + 1)).map(PathBuf::from); + if action == "uninstall" && !owns_driver() { + if let Some(f) = &result { + let _ = std::fs::write(f, ""); + } + return Some(NOTHING_TO_REMOVE); + } let outcome = match (action, driver_dir()) { (_, None) => Err("앱 폴더를 찾지 못했습니다".to_owned()), ("install", Some(d)) => install(&d), @@ -142,6 +152,14 @@ pub fn elevated_main(args: &[String]) -> Option { Some(if outcome.is_ok() { 0 } else { 1 }) } +/// Whether this app's driver (or something it left) is on the PC. +fn owns_driver() -> bool { + #[cfg(windows)] + return win::ours(); + #[cfg(not(windows))] + false +} + #[cfg(not(windows))] fn install(_driver: &Path) -> Result<(), String> { Err("가상 모니터는 Windows에서만 씁니다".into()) @@ -249,7 +267,7 @@ mod win { (r == ERROR_SUCCESS).then(|| text(&buf)) } - fn ours() -> bool { + pub(super) fn ours() -> bool { match (vdd_path(), config_dir()) { (Some(p), Some(c)) => p.trim_end_matches('\\').eq_ignore_ascii_case(c.to_string_lossy().trim_end_matches('\\')), _ => false, @@ -558,6 +576,7 @@ mod win { let _ = std::fs::remove_file(&result); match code { 0 => Ok(()), + c if c as i32 == super::NOTHING_TO_REMOVE && action == "uninstall" => Ok(()), _ if !why.is_empty() => Err(why), c => Err(format!("드라이버 작업이 실패했습니다 (종료 코드 {c})")), } @@ -653,4 +672,17 @@ mod tests { fn only_the_display_driver_option_runs_the_elevated_half() { assert_eq!(elevated_main(&["jarvis".into(), "--location".into(), "x".into()]), None); } + + #[test] + fn removing_a_driver_this_app_does_not_own_says_there_is_nothing_to_remove() { + // The uninstaller goes on with code 2, and stops on a failure (code 1). + let result = std::env::temp_dir().join(format!("jarvis-vdd-test-{}.txt", std::process::id())); + let args: Vec = ["jarvis", "--display-driver", "uninstall", "--result", result.to_str().unwrap()] + .map(String::from).into(); + assert_eq!(elevated_main(&args), Some(NOTHING_TO_REMOVE)); + assert_eq!(std::fs::read_to_string(&result).unwrap(), ""); + let _ = std::fs::remove_file(&result); + let bad: Vec = ["jarvis", "--display-driver", "nope"].map(String::from).into(); + assert_eq!(elevated_main(&bad), Some(1)); + } }