diff --git a/CMakeLists.txt b/CMakeLists.txt index af2abf9..eba3f9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.88 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.89 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() @@ -47,6 +47,7 @@ target_link_libraries(KSwitcherFiles PRIVATE kscore) target_include_directories(kscore PUBLIC src PRIVATE vendor) target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00) target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore) +set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1") add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc) target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP) target_link_libraries(KSwitcher PRIVATE kscore) diff --git a/FILES-UI.md b/FILES-UI.md index 41a7da0..f8a29ff 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -39,6 +39,19 @@ Far Manager є зразком для оформлення файлового м Command history → Allow paired PCs to run PowerShell commands here**. Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Команди запускаються без підвищених прав. Для цієї функції оновіть обидва ПК. +- **F9 → Commands → Hibernate remote PC** доступна для активної LAN-панелі. + У підтвердженні показується ім’я цільового ПК. На цільовому ПК ввімкніть + **Options → Command line → Command history → Allow paired PCs to hibernate this PC**. + Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії + потрібні оновлення на обох ПК і ввімкнена гібернація Windows. +- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для + ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files + відправника. На цільовому ПК потрібен дозвіл **Options → Command line → + Command history → Allow paired PCs to update KSwitcher here**. Після + перевірки нового стабільного пакета оновлювач без запитань закриває + KSwitcher, Files, Config і редактори скриншотів цієї інсталяції. + Незбережені зміни у примусово закритих вікнах втрачаються. + Закриття процесів і результат записуються до `kswitcher.log`. - Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію курсора командного рядка або замінює виділення. Подвійні лапки додаються diff --git a/Release/KSwitcher-win-x64.zip b/Release/KSwitcher-win-x64.zip index f0e4a83..2093b6d 100644 Binary files a/Release/KSwitcher-win-x64.zip and b/Release/KSwitcher-win-x64.zip differ diff --git a/Release/README.md b/Release/README.md index b4c928d..cba4bc5 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,11 @@ # Latest Windows release +## v0.6.89 — 2026-11-16 + +In Files, Commands now offers **Hibernate remote PC** and **Update remote KSwitcher** for the active LAN pane. The target PC has separate, default-off permissions for each action. Unattended updates verify the stable package, close the target installation's Files, Config and screenshot windows, and restart KSwitcher. Forced closure discards unsaved changes. The target journal records closed processes and the update result. + +**Українською.** У меню Commands з’явилися **Hibernate remote PC** і **Update remote KSwitcher** для активної LAN-панелі. На цільовому ПК кожна дія має окремий дозвіл, вимкнений за замовчуванням. Оновлювач перевіряє стабільний пакет, без запитань закриває Files, Config і редактори скриншотів цієї інсталяції та перезапускає KSwitcher. Примусове закриття відкидає незбережені зміни. Журнал цільового ПК фіксує закриті процеси й результат оновлення. + ## v0.6.88 — 2026-11-16 In Files, Ctrl+Enter inserts the name of the file or folder under the active pane cursor into the command line. An open Files window can still request the LAN peer list after KSwitcher updates and restarts. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 7c52d83..af0aaba 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -d48e590580801a39a08ac8f5192983610e0a3fec9e5b0cf7f01a40a063cbed78 KSwitcher-win-x64.zip +06d74702f466c8f793fafbbf54942fd1688e36f975b4d709652bbdb023e2fc2f KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index 72add72..4f82674 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,24 +1,26 @@ { + "schema": 1, + "version": "0.6.89", "files": [ { "path": "KSwitcher.exe", - "sha256": "aa542387388904d2a8df98bdef0e0b25b12aa294ded279f3308553d762086fee", - "size": 5852660 + "sha256": "411340c538f2b76424b7e4d228c217ab1b56e059ee640c109888f59115d9d5ec", + "size": 2465792 }, { "path": "KSwitcher.Config.exe", - "sha256": "c128e8affc7485ba475228ca9bee6915948208405bd84110ffc776ebf8a3d0da", - "size": 5917446 + "sha256": "f48c68669147e32090823465639d8301798f2e4934e160becd1b5fd42d6708bb", + "size": 2445824 }, { "path": "KSwitcher.Screenshot.exe", - "sha256": "82397c1e4d73415449ba7389a716d6e1ec4dab2310b1471369f467435b771762", - "size": 5747437 + "sha256": "311ebf1a3d135fe6ce8bfd0978a9552fbb64c7d7f9a791f4aa4c5bd2c439f06f", + "size": 3052544 }, { "path": "KSwitcher.Files.exe", - "sha256": "c86b7ff32468bafa6f658a810f475b557f47a23ba42a1739db09d7eeab6fb533", - "size": 8159101 + "sha256": "73acd9be067451c3db83706be0164959f2ac130259c41c48841d16d1aa2792d5", + "size": 3671552 }, { "path": "WebView2Loader.dll", @@ -122,15 +124,13 @@ }, { "path": "tools/StayHere.exe", - "sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c", - "size": 540583 + "sha256": "2b214b0ed2b6f754611f3355ccdcc6797c6bc5c2aac70bd51e060ba25eb4c3a5", + "size": 133120 }, { "path": "tools/StayHere-README.md", "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", "size": 2796 } - ], - "version": "0.6.88", - "schema": 1 + ] } diff --git a/resources/app.rc b/resources/app.rc index 55de70f..ba965dc 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,6,88,0 - PRODUCTVERSION 0,6,88,0 + FILEVERSION 0,6,89,0 + PRODUCTVERSION 0,6,89,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -20,7 +20,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.6.88" + VALUE "FileVersion", "0.6.89" END END BLOCK "VarFileInfo" diff --git a/resources/files.rc b/resources/files.rc index a287002..342a4f3 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -115,6 +115,8 @@ BEGIN LTEXT "Open command history", 322, 131, 53, 120, 12 CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15 AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14 + AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14 + AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14 PUSHBUTTON "Reset selected to defaults", 284, 131, 181, 125, 15 COMBOBOX 285, 131, 183, 139, 95, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL PUSHBUTTON "Reset property", 286, 278, 183, 108, 15 diff --git a/resources/update.ps1 b/resources/update.ps1 index cda2c2e..f6f422f 100644 --- a/resources/update.ps1 +++ b/resources/update.ps1 @@ -4,6 +4,7 @@ [string]$InstallDirectory, [string]$WorkDirectory, [int]$ParentProcessId, [string]$ReadyEvent, [switch]$ShowProgress, + [switch]$Unattended, [string]$Journal, [switch]$Library ) $ErrorActionPreference = 'Stop' @@ -408,12 +409,30 @@ function Undo-Files([string]$Target,[string]$Backup,[Collections.Generic.List[st function Write-Result($Value) { $Value | ConvertTo-Json -Compress | Set-Content -LiteralPath (Join-Path $WorkDirectory 'result.json') -Encoding UTF8 } +function Write-UpdateJournal([string]$Message) { + if (!$Journal) { return } + [IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') LAN update: $Message`n", + [Text.UTF8Encoding]::new($false)) +} +function Stop-UpdateCompanions([string]$Directory) { + $root = [IO.Path]::GetFullPath($Directory).TrimEnd('\') + $prefix = [regex]::Escape($root + '\') + $pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?KSwitcher\.(?:Config|Screenshot|Files)\.exe$' + foreach ($process in @(Get-Process 'KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files' -ErrorAction SilentlyContinue)) { + if ($process.Path -notmatch $pattern) { continue } + Write-UpdateJournal "Closing $($process.ProcessName) (PID $($process.Id))." + if (!$process.HasExited) { + try { $process.Kill() } catch { if (!$process.HasExited) { throw } } + if (!$process.WaitForExit(10000)) { throw "Could not close $($process.ProcessName) (PID $($process.Id))." } + } + } +} if ($Library) { return } $transaction = $null; $parentProcess = $null; $ready = $null; $started = $null $changed = [Collections.Generic.List[string]]::new() $parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null; $uiFinished = $false try { - if ($ShowProgress -or $Mode -eq 'Install') { Start-UpdateProgress } + if (!$Unattended -and ($ShowProgress -or $Mode -eq 'Install')) { Start-UpdateProgress } $current = Get-StableVersion $CurrentVersion if (!$current) { throw 'Invalid installed version.' } if ($Mode -eq 'Install') { @@ -426,9 +445,12 @@ try { $metadata = Join-Path $WorkDirectory 'releases.json' Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB $release = Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) $current - if (!$release) { Write-Result @{state='current'}; exit 0 } + if (!$release) { + if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." } + Write-Result @{state='current'}; exit 0 + } if ($Mode -eq 'Check') { Write-Result @{state='available';version=$release.version}; exit 0 } - if ($ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' } + if (!$Unattended -and $ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' } Assert-PlainDirectory $InstallDirectory $transaction = Join-Path $InstallDirectory ('.kswitcher-update-'+[guid]::NewGuid().ToString('N')) $stage = Join-Path $transaction 'stage'; $backup = Join-Path $transaction 'backup' @@ -442,12 +464,18 @@ try { Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files' Expand-Release $archive $stage (Get-StableVersion $release.version) $screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe')) - if (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath }) { throw 'Close screenshot editors before installing an update.' } + if (!$Unattended -and (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath })) { + throw 'Close screenshot editors before installing an update.' + } + if ($Unattended) { + Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)." + } Write-Result @{state='prepared';version=$release.version} Show-UpdateProgress 'Closing KSwitcher' 'Waiting for the running application to exit safely' $ready.Set() | Out-Null if (!$parentProcess.WaitForExit(120000)) { throw 'KSwitcher did not exit; the installed files were not changed.' } $parentExited = $true + if ($Unattended) { Stop-UpdateCompanions $InstallDirectory } Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data' Install-Files $stage $InstallDirectory $backup $changed $startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N') @@ -456,6 +484,9 @@ try { $child = Start-Process -FilePath (Join-Path $InstallDirectory 'KSwitcher.exe') -ArgumentList "--update-ready-event=$startedName" -WorkingDirectory $InstallDirectory -WindowStyle Hidden -PassThru if (!$started.WaitOne(30000) -or $child.HasExited) { throw 'The updated application did not confirm startup.' } $success = $true + if ($Unattended) { + try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {} + } if ($script:progressWindow) { $uiFinished = Complete-UpdateProgress 'Update completed' "KSwitcher $(Get-StableVersion $release.version) is now running." $true } @@ -474,7 +505,10 @@ try { } } Write-Result @{state='error';error=$message} - if ($ready -and $ready.WaitOne(0)) { + if ($Unattended) { + try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {} + } + if (!$Unattended -and $ready -and $ready.WaitOne(0)) { if ($script:progressWindow) { $uiFinished = Complete-UpdateProgress 'Update failed' $message $false } else { diff --git a/src/app.cpp b/src/app.cpp index 935aaec..337f90b 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -4,6 +4,7 @@ #include "../resources/resource.h" #include "ocr.h" #include "lan_clipboard_image.h" +#include "lan_files.h" #include "configuration.h" #include "diagnostics.h" #include "paste_probe.h" @@ -2941,12 +2942,12 @@ void App::trayMenu() void App::checkUpdate(bool interactive, bool install, const std::wstring &version) { if (updateRunning) return; - if (install && FindWindowW(L"KSwitcher.Config", nullptr)) + if (install && interactive && FindWindowW(L"KSwitcher.Config", nullptr)) { report(L"Close the configurator before installing an update."); return; } - if (install && busy) + if (install && interactive && busy) { report(L"Wait for the current text operation to finish, then select Update again."); return; @@ -3006,6 +3007,16 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) } switch (msg) { + case LanUpdateRequestedMessage: + if (!lan::remoteUpdateAllowed()) return 0; + if (app->updateRunning) + log(L"LAN update request ignored because an update is already running."); + else + { + log(L"Starting unattended KSwitcher update requested over LAN."); + app->checkUpdate(false, true); + } + return 0; case UpdateMessage: { std::unique_ptr result(reinterpret_cast(lp)); diff --git a/src/files_main.cpp b/src/files_main.cpp index 52ce455..12fd7a7 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -332,6 +332,7 @@ HWND drivePeerService{}; bool drivePeerReplyReceived{}; std::wstring drivePeerLookupError; std::vector drivePeers; +std::future pendingPeerAction; struct DriveQuery { FilesPeer peer; @@ -1418,6 +1419,65 @@ void prepareTextDialog(HWND dialog); void showTextMessage(HWND owner,const wchar_t *text); void editTextOptions(HWND owner,bool edit); +void runActivePeerAction(HWND owner,bool update) +{ + if(!panels[active].peer) return; + if(pendingPeerAction.valid()) + { + setStatus(L"A remote PC request is already in progress."); + return; + } + const auto peer=*panels[active].peer; + const auto question=update + ? L"Update KSwitcher on "+peer.name+L"? Open KSwitcher windows there will close if an update is available." + : L"Hibernate "+peer.name+L"?"; + if(showFilesNotice(owner,question.c_str(),update?L"Update remote KSwitcher":L"Hibernate remote PC",true)!=IDYES) + return; + + std::packaged_task task([peer,update] + { + const auto prefix=peer.name+L": "; + const auto unconfirmed=prefix+(update?L"Could not confirm receipt of the update request." + :L"Hibernation could not be confirmed."); + try + { + FilesConnection host(&peer); + checkFileReply(host.call({{"action",update?"update":"hibernate"}})); + return prefix+(update?L"Update requested. See the remote KSwitcher log for the result." + :L"Windows accepted the hibernation request."); + } + catch(const std::system_error &error) + { + switch(error.code().value()) + { + case ERROR_ACCESS_DENIED: + return prefix+(update?L"Remote updates are disabled. Check Files settings on this PC." + :L"Hibernation is not allowed. Check the remote Files settings."); + case ERROR_INVALID_FUNCTION: + return prefix+(update?L"This version of KSwitcher cannot accept remote update requests." + :L"Update KSwitcher to enable remote hibernation."); + case ERROR_PRIVILEGE_NOT_HELD: + return prefix+L"Windows denied the hibernation privilege."; + default: + return unconfirmed+L" "+fileError(error); + } + } + catch(const std::exception &) + { + return unconfirmed; + } + }); + pendingPeerAction=task.get_future(); + try {std::thread(std::move(task)).detach();} + catch(const std::system_error &error) + { + pendingPeerAction={}; + setStatus(fileError(error)); + return; + } + setStatus((update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"..."); +} + void selectDrive() { auto row=SendMessageW(picker,LB_GETCURSEL,0,0); @@ -1440,6 +1500,7 @@ void selectDrive() } else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1); else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true); + else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7); else { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -4236,8 +4297,16 @@ void openMenu(HWND window, int index) index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"}; } else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"}; - else if(index==2) rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", - L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"}; + else if(index==2) + { + rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", + L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"}; + if(panels[active].peer) + { + rows.push_back(L"Hibernate remote PC"); + rows.push_back(L"Update remote KSwitcher"); + } + } std::set used; commandAccessPositions.assign(rows.size(),std::wstring::npos); const auto reserve=[&](size_t row,wchar_t key) @@ -4451,7 +4520,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } case WM_TIMER: if(wp==driveQueryTimer) {pollDriveQueries(window);return 0;} - if(wp==terminalTimer) { updateTerminalOutput(); return 0; } + if(wp==terminalTimer) + { + if(pendingPeerAction.valid() && + pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready) + setStatus(pendingPeerAction.get()); + updateTerminalOutput(); + return 0; + } if(wp==directoryWatchTimer) { refreshChangedPanels(); return 0; } if(wp!=transferHighlightTimer) break; ++transferHighlightPhase; diff --git a/src/files_options.inl b/src/files_options.inl index 9a3ead4..acd81c2 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -1,5 +1,5 @@ constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286, - optionsRemoteTerminal=370; + optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372; enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions }; constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"}; constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background", @@ -80,6 +80,8 @@ struct OptionsBaseline std::vector styles=fileStyles; std::array keys=commandHistoryKeys; bool remoteTerminal=ks::lan::remoteTerminalAllowed(); + bool remoteHibernate=ks::lan::remoteHibernateAllowed(); + bool remoteUpdate=ks::lan::remoteUpdateAllowed(); DWORD width=static_cast(sizeWidth), fields=statusFields; bool extensions=alignExtensions, folders=alignFolders, details=showDetails; std::array wide{panels[0].wide,panels[1].wide}; @@ -154,6 +156,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles || draft.framePadding!=base.padding || optionsFontChanged(draft) || optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal || + checked(optionsRemoteHibernate)!=base.remoteHibernate || + checked(optionsRemoteUpdate)!=base.remoteUpdate || draft.text!=base.text; EnableWindow(GetDlgItem(dialog,optionsApply),dirty); InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE); @@ -423,7 +427,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) for(const auto &option:frameOptions) SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0); } - constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal}; + constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate}; show(commandLineControls,page==CommandLine && section==0); show(textControls,textOptionsPage(page)); show(editingControls,page==TextEditor); @@ -519,7 +523,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft) matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground")); } else if(page==CommandLine) addSection(L"Command history",0, - matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here")); + matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") || + matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here")); else if(textOptionsPage(page)) { const bool propertyMatches=matches(L"Tab width") || @@ -584,6 +589,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u); setOptionHistoryKeys(dialog,commandHistoryKeys); CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed()); + CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed()); + CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed()); filterOptions(dialog,draft); updateOptionsApply(dialog,draft); return TRUE; @@ -701,6 +708,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { setOptionHistoryKeys(dialog,defaultHistoryKeys); CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED); + CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED); + CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED); } if(draft->page==allOptions || draft->page==PanelModes) for(const auto &property:panelProperties) @@ -740,7 +749,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: - case 273: case 274: case optionsRemoteTerminal: + case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate: updateOptionsApply(dialog,*draft); return TRUE; case 321: case 323: @@ -841,6 +850,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]); saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]); saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal); + saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate); + saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate); saveChanged(L"SizeWidth",width,base.width); saveChanged(L"AlignExtensions",checked(202),base.extensions); saveChanged(L"AlignFolders",checked(204),base.folders); @@ -887,6 +898,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u); setOptionHistoryKeys(dialog,commandHistoryKeys); CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed()); + CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed()); + CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed()); if(draft->page==PanelColors && draft->section==fileStyleSection) updateFileStyleEditor(dialog,*draft,true); showOptionsPage(dialog,*draft,draft->page,draft->section); diff --git a/src/lan.cpp b/src/lan.cpp index 0f112b6..c0d94c5 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -295,7 +295,12 @@ struct LanService::Impl { std::lock_guard lock(mutex); return !stopping && trusted.contains(peer)?trusted.at(peer).at("key").get():std::string{}; - },lan::FilesPort,lan::remoteTerminalAllowed); + },lan::FilesPort,lan::remoteTerminalAllowed,lan::hibernateFromPairedPC,[this]() -> DWORD + { + if(!lan::remoteUpdateAllowed()) return ERROR_ACCESS_DENIED; + if(!inputWindow) return ERROR_INVALID_WINDOW_HANDLE; + return PostMessageW(inputWindow,LanUpdateRequestedMessage,0,0)?ERROR_SUCCESS:GetLastError(); + }); hub.datagrams([&](const auto &target,const auto &packet){ std::lock_guard lock(mutex); if(shareInput&&trusted.contains(target)&&peers.contains(target))send(socket,peers.at(target).address,packet); diff --git a/src/lan.h b/src/lan.h index 4a2c7fa..6e3a3e2 100644 --- a/src/lan.h +++ b/src/lan.h @@ -6,6 +6,7 @@ namespace ks { inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69; inline constexpr UINT LanFilesChangedMessage=WM_APP+70; +inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90; struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};}; // Discovery, pairing and optional encrypted input within the resident process. class LanService diff --git a/src/lan_files.cpp b/src/lan_files.cpp index f5be44d..90caf9f 100644 --- a/src/lan_files.cpp +++ b/src/lan_files.cpp @@ -33,13 +33,17 @@ void checkFileReply(const Json &reply) if(error) throw std::system_error(static_cast(error),std::system_category()); } -bool remoteTerminalAllowed() +static bool filesPermissionEnabled(const wchar_t *name) { DWORD allowed{},size=sizeof(allowed); - return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",remoteTerminalPreference, + return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",name, RRF_RT_REG_DWORD,nullptr,&allowed,&size)==ERROR_SUCCESS && allowed==1; } +bool remoteTerminalAllowed() {return filesPermissionEnabled(remoteTerminalPreference);} +bool remoteHibernateAllowed() {return filesPermissionEnabled(remoteHibernatePreference);} +bool remoteUpdateAllowed() {return filesPermissionEnabled(remoteUpdatePreference);} + bool recycleFile(HWND owner,const fs::path &path) { const auto initialized=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED); @@ -232,6 +236,27 @@ struct FileHandle ~FileHandle(){close();} }; +DWORD requestSystemHibernate() +{ + wchar_t system[MAX_PATH]{}; + const auto length=GetSystemDirectoryW(system,MAX_PATH); + if(!length) return GetLastError(); + if(length>=MAX_PATH) return ERROR_INSUFFICIENT_BUFFER; + const auto executable=fs::path(system)/L"shutdown.exe"; + wchar_t command[]=L"shutdown.exe /h"; + STARTUPINFOW startup{sizeof(startup)}; + PROCESS_INFORMATION child{}; + if(!CreateProcessW(executable.c_str(),command,nullptr,nullptr,FALSE,CREATE_NO_WINDOW, + nullptr,system,&startup,&child)) return GetLastError(); + CloseHandle(child.hThread); + FileHandle process{child.hProcess}; + const auto wait=WaitForSingleObject(process.value,3000); + if(wait==WAIT_TIMEOUT) return ERROR_TIMEOUT; + if(wait!=WAIT_OBJECT_0) return GetLastError(); + DWORD exitCode{}; + return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError(); +} + struct RemoteCommand { FileHandle job,process,output; @@ -403,6 +428,7 @@ std::string hashPrefix(HANDLE file,uint64_t size,const FileProgress &progress,ui class FileOperations { FilesListener::TerminalPermission terminalPermission; + FilesListener::HostAction hibernate,update; RemoteCommand terminal; bool remote; HANDLE search=INVALID_HANDLE_VALUE; @@ -558,8 +584,10 @@ class FileOperations return reply; } public: - explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={}): - terminalPermission(std::move(permission)),remote(remote){} + explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={}, + FilesListener::HostAction hibernateAction={},FilesListener::HostAction updateAction={}): + terminalPermission(std::move(permission)),hibernate(std::move(hibernateAction)), + update(std::move(updateAction)),remote(remote){} ~FileOperations(){closeSearch();discard();} Json call(const Json &request,const FileProgress &progress) { @@ -573,6 +601,14 @@ public: Json perform(const Json &request,const FileProgress &progress) { const auto action=request.at("action").get(); + if(action=="hibernate" || action=="update") + { + if(request.size()!=1) return failure(ERROR_INVALID_PARAMETER); + const auto &hostAction=action=="hibernate"?hibernate:update; + if(!remote || !hostAction) return failure(ERROR_ACCESS_DENIED); + const auto error=hostAction(); + return error?failure(error):ok(); + } if(action=="terminalRun" || action=="terminalPoll" || action=="terminalCancel") { if(!remote || !terminalPermission || !terminalPermission()) @@ -865,6 +901,12 @@ struct FilesConnection::Impl } }; +DWORD hibernateFromPairedPC() +{ + if(!remoteHibernateAllowed()) return ERROR_ACCESS_DENIED; + return requestSystemHibernate(); +} + FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique(peer)){} FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key): impl(std::make_unique()) @@ -986,11 +1028,14 @@ struct FilesListener::Impl std::string local; PairKey key; TerminalPermission terminalPermission; + HostAction hibernate,update; WinSocket listener; std::vector> clients; uint16_t boundPort{}; - Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission): - local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)) + Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission,HostAction hibernateAction, + HostAction updateAction): + local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)), + hibernate(std::move(hibernateAction)),update(std::move(updateAction)) { listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(listener.value==INVALID_SOCKET) return; @@ -1025,7 +1070,7 @@ struct FilesListener::Impl wire.authenticate(secret,peer,local,challenge,nonce,false); if(wire.read().at("action")!="authenticate") return; wire.write(ok()); - FileOperations operations(true,terminalPermission); + FileOperations operations(true,terminalPermission,hibernate,update); for(;;) { const auto request=wire.read(true); @@ -1066,8 +1111,10 @@ struct FilesListener::Impl } }; -FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission): - impl(std::make_unique(std::move(local),std::move(key),port,std::move(terminalPermission))){} +FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission, + HostAction hibernate,HostAction update): + impl(std::make_unique(std::move(local),std::move(key),port,std::move(terminalPermission), + std::move(hibernate),std::move(update))){} FilesListener::~FilesListener()=default; uint16_t FilesListener::port()const{return impl->boundPort;} void FilesListener::poll(){impl->poll();} diff --git a/src/lan_files.h b/src/lan_files.h index 35646b6..102dcba 100644 --- a/src/lan_files.h +++ b/src/lan_files.h @@ -42,7 +42,9 @@ class FilesListener public: using PairKey = std::function; using TerminalPermission = std::function; - FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={}); + using HostAction = std::function; + FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={}, + HostAction hibernate={},HostAction update={}); uint16_t port() const; ~FilesListener(); void poll(); @@ -54,4 +56,9 @@ void checkFileReply(const Json &reply); bool recycleFile(HWND owner, const std::filesystem::path &path); inline constexpr wchar_t remoteTerminalPreference[]=L"AllowRemoteTerminal"; bool remoteTerminalAllowed(); +inline constexpr wchar_t remoteHibernatePreference[]=L"AllowRemoteHibernate"; +bool remoteHibernateAllowed(); +DWORD hibernateFromPairedPC(); +inline constexpr wchar_t remoteUpdatePreference[]=L"AllowRemoteUpdate"; +bool remoteUpdateAllowed(); } diff --git a/src/update.cpp b/src/update.cpp index 39e485a..6c28abd 100644 --- a/src/update.cpp +++ b/src/update.cpp @@ -55,7 +55,12 @@ UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool s L" -CurrentVersion " + quoteArgument(AppVersion) + L" -WorkDirectory " + quoteArgument(work.wstring()) + L" -InstallDirectory " + quoteArgument(std::filesystem::path(executable()).parent_path().wstring()) + L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteArgument(readyName); - if (install) command += L" -ExpectedVersion " + quoteArgument(expectedVersion); + if (install && expectedVersion.empty()) + { + command += L" -Unattended -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring()); + } + else if (install) + command += L" -ExpectedVersion " + quoteArgument(expectedVersion); if (showProgress) command += L" -ShowProgress"; STARTUPINFOW startup{sizeof(startup)}; PROCESS_INFORMATION process{}; diff --git a/src/update.h b/src/update.h index 467ec9a..96e7b2d 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.6.88"; +inline constexpr wchar_t AppVersion[] = L"0.6.89"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/lan_files.cpp b/tests/lan_files.cpp index 7404859..1ea9feb 100644 --- a/tests/lan_files.cpp +++ b/tests/lan_files.cpp @@ -134,7 +134,11 @@ int main() const auto client=randomHex(16),first=randomHex(16),second=randomHex(16),key=randomHex(32); auto lookup=[&](const std::string &id){return id==client?key:std::string{};}; std::atomic allowTerminal{}; - FilesListener a(first,lookup,0,[&]{return allowTerminal.load();}),b(second,lookup,0); + std::atomic hibernateRequests{}; + std::atomic updateRequests{}; + FilesListener a(first,lookup,0,[&]{return allowTerminal.load();}), + b(second,lookup,0,{},[&]{++hibernateRequests;return ERROR_SUCCESS;}, + [&]{++updateRequests;return ERROR_SUCCESS;}); require(a.port() && b.port() && a.port()!=b.port(),"test listeners unavailable"); std::jthread polling([&](std::stop_token stop) { @@ -152,6 +156,26 @@ int main() } catch(const std::system_error &){} FilesConnection host(one,client,key); + { + const Json hibernate={{"action","hibernate"}}; + FilesConnection target(two,client,key); + FilesConnection local; + require(local.call(hibernate).at("error")==ERROR_ACCESS_DENIED, + "local file operations cannot dispatch the LAN power action"); + require(host.call(hibernate).at("error")==ERROR_ACCESS_DENIED && hibernateRequests==0, + "hibernate requires a separately enabled handler on the target"); + require(target.call({{"action","hibernate"},{"command","anything"}}).at("error") + ==ERROR_INVALID_PARAMETER && hibernateRequests==0,"hibernate accepts no extra parameters"); + require(target.call(hibernate).at("error")==ERROR_SUCCESS && hibernateRequests==1, + "hibernate dispatches only to the addressed paired PC"); + const Json update={{"action","update"}}; + require(host.call(update).at("error")==ERROR_ACCESS_DENIED && updateRequests==0, + "update requires a separate handler on the target"); + require(target.call({{"action","update"},{"url","https://example.invalid"}}).at("error") + ==ERROR_INVALID_PARAMETER && updateRequests==0,"update cannot supply an external package"); + require(target.call(update).at("error")==ERROR_SUCCESS && updateRequests==1 && hibernateRequests==1, + "update dispatches to the addressed paired PC without invoking hibernate"); + } auto deniedCommand=fileRequest("terminalRun",root); deniedCommand["command"]="Write-Output denied"; require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed without consent"); diff --git a/tests/update.ps1 b/tests/update.ps1 index d764487..1bc4fc5 100644 --- a/tests/update.ps1 +++ b/tests/update.ps1 @@ -7,6 +7,33 @@ function Reject([scriptblock]$Action,[string]$Name) { $rejected=$false; try { & $root=Join-Path ([IO.Path]::GetTempPath()) ('KSwitcher-update-tests-'+[guid]::NewGuid().ToString('N')) [IO.Directory]::CreateDirectory($root) | Out-Null try { + $companionRoot=Join-Path $root 'companion-install' + $otherRoot=Join-Path $root 'other-install' + [IO.Directory]::CreateDirectory($companionRoot) | Out-Null + [IO.Directory]::CreateDirectory($otherRoot) | Out-Null + $companions=@() + $Journal=Join-Path $root 'update.log' + try { + foreach ($fixture in @( + @{Root=$companionRoot; Name='KSwitcher.Files.exe'}, + @{Root=$companionRoot; Name='KSwitcher.Screenshot.exe'}, + @{Root=$companionRoot; Name='KSwitcher.Config.exe'}, + @{Root=$otherRoot; Name='KSwitcher.Files.exe'})) { + $path=Join-Path $fixture.Root $fixture.Name + Copy-Item -LiteralPath (Join-Path ([Environment]::SystemDirectory) 'ping.exe') -Destination $path + $companions+=Start-Process -FilePath $path -ArgumentList '-t','127.0.0.1' -WindowStyle Hidden -PassThru + } + Stop-UpdateCompanions $companionRoot + Assert (@($companions[0..2] | Where-Object HasExited).Count -eq 3) 'unattended update closes all companions in its installation' + Assert (!$companions[3].HasExited) 'unattended update leaves a companion from another installation running' + Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'LAN update: Closing KSwitcher\.' }).Count -eq 3) 'unattended update journals every companion closure' + } finally { + foreach ($companion in $companions) { + if (!$companion.HasExited) { $companion.Kill(); $companion.WaitForExit() } + $companion.Dispose() + } + $Journal=$null + } $binaryInfo = [Diagnostics.FileVersionInfo]::GetVersionInfo((Resolve-Path -LiteralPath $Executable).Path) $binaryVersion = Get-StableVersion $binaryInfo.FileVersion Assert ($null -ne $binaryVersion) 'executable has a stable version'