From bdd058f4935c57886c0ffbc573dd19ee1941b8fa Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Fri, 20 Nov 2026 20:40:01 +0200 Subject: [PATCH] Release KSwitcher v0.6.123 (#69) Ship the offline tray state and discovery-driven LAN input reconnection. Include the verified Windows x64 package manifest and checksum. --- CMakeLists.txt | 2 +- LAN-PREVIEW.md | 14 ++-- Release/README.md | 10 +++ Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 138 ++++++++++++++++++------------------- resources/app.rc | 6 +- src/app.cpp | 20 +++--- src/lan.cpp | 66 ++++++++++++------ src/lan.h | 3 +- src/lan_channel.cpp | 30 +++++--- src/lan_channel.h | 9 ++- src/update.h | 2 +- tests/lan_input.cpp | 47 +++++++++++-- 13 files changed, 226 insertions(+), 123 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cd79409..1f846fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.122 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.123 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/LAN-PREVIEW.md b/LAN-PREVIEW.md index 4606320..e77f484 100644 --- a/LAN-PREVIEW.md +++ b/LAN-PREVIEW.md @@ -59,10 +59,11 @@ the local resident process running and log downloads enabled on the remote PC. into the source computer restores its cursor at the corresponding edge. Empty cells, diagonal-only neighbors and offline PCs do not transfer control. -When input sharing is enabled, the KSwitcher tray icon shows a green dot while -all paired PCs are connected, a pulsing amber dot while connections are pending, -and a red dot if the LAN worker stops. Hover over the icon to see how many PCs -are connected while KSwitcher retries. +When input sharing is enabled, the tray icon shows a steady gray dot if all +paired PCs are offline, a pulsing amber dot while a discovered PC is connecting, +a green dot when all online paired PCs are connected, and a red dot if the LAN +worker stops. Hover over the icon to see the connection status and the connected +count when only some paired PCs are connected. The source cursor is parked and hidden beneath a tiny no-activation window. A small banner identifies remote control; no full-screen layered bitmap is retained. @@ -110,6 +111,11 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet. A second LAN-enabled KSwitcher cannot use the same ports on one computer. Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds. +LAN discovery authenticates paired PCs before starting new input connections. +Discovery remains active while all paired PCs are offline and wakes input sharing +when one reappears. An authenticated input connection survives missed discovery +announcements. Once discovery has expired and the channel closes, further input +attempts wait for fresh discovery. After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the discovery socket (UDP 45883) once its current TCP connection attempt has failed or reached its 10-second deadline. diff --git a/Release/README.md b/Release/README.md index 9e3e6a4..115350a 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,15 @@ # Latest Windows release +## v0.6.123 — 2026-11-20 + +- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected. +- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears. + +**Українською.** + +- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані. +- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК. + ## v0.6.122 — 2026-11-20 - LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 8f78a9d..24a61a7 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -074dce23470876852c0006cece4becf64e42a616a72e3502857fe76beed505d5 KSwitcher-win-x64.zip +868941978ca231f3df01917277d8ec5b8de970c81f6b83b5fa9e64b18b71ab9a KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index b3828c5..0557bf1 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,166 +1,166 @@ { "schema": 1, - "version": "0.6.122", + "version": "0.6.123", "files": [ { - "size": 5892662, - "path": "KSwitcher.exe", - "sha256": "10d2dbdec8dbc9b8c051a5befdec61319c4532ddcf3dfb3f4484d60feca593e1" + "size": 5892884, + "sha256": "043c10eb6752656fc2aa6c1f8d329d4fe243347a5275088e5dc4385638acd870", + "path": "KSwitcher.exe" }, { - "size": 5948775, - "path": "KSwitcher.Config.exe", - "sha256": "4bc59946afd29f843be98e4b0389cc1c40363ecc50a3598629af074adb7abe25" + "size": 5948997, + "sha256": "ac6368858b86d4e9a4a2c1cf4cd90c39b58d699909c417f73d9f882c54dd96a0", + "path": "KSwitcher.Config.exe" }, { "size": 5763947, - "path": "KSwitcher.Screenshot.exe", - "sha256": "4444dd1f7efd4e607833699fd841f50c6f04094da024474b705fb8247ec4fbe8" + "sha256": "d2f435c645419a155e6feac7761d9894f7bd2099cd695a93650847c869c50ffb", + "path": "KSwitcher.Screenshot.exe" }, { - "size": 9395091, - "path": "KSwitcher.Files.exe", - "sha256": "140455238ce9fa909dbb550d1c67ff6ff1aa2eebdfa8297183cc5d0b16ce14a0" + "size": 9395313, + "sha256": "43512aa25c8b9854cb3134b9480e24049eab77a0008af55cede06369dc6a0964", + "path": "KSwitcher.Files.exe" }, { "size": 194912, - "path": "WebView2Loader.dll", - "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6" + "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", + "path": "WebView2Loader.dll" }, { "size": 1103, - "path": "terminal/addon-fit-LICENSE.txt", - "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f" + "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", + "path": "terminal/addon-fit-LICENSE.txt" }, { "size": 1521, - "path": "terminal/addon-fit.js", - "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527" + "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", + "path": "terminal/addon-fit.js" }, { "size": 527, - "path": "terminal/index.html", - "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef" + "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", + "path": "terminal/index.html" }, { "size": 1073, - "path": "terminal/markdown-it-LICENSE.txt", - "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473" + "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", + "path": "terminal/markdown-it-LICENSE.txt" }, { "size": 100786, - "path": "terminal/markdown-it.js", - "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e" + "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", + "path": "terminal/markdown-it.js" }, { "size": 3599, - "path": "terminal/markdown.html", - "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094" + "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094", + "path": "terminal/markdown.html" }, { "size": 17575, - "path": "terminal/markdown.js", - "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8" + "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8", + "path": "terminal/markdown.js" }, { "size": 1089, - "path": "terminal/mermaid-LICENSE.txt", - "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80" + "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", + "path": "terminal/mermaid-LICENSE.txt" }, { "size": 5537838, - "path": "terminal/mermaid.js", - "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3" + "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", + "path": "terminal/mermaid.js" }, { "size": 5065, - "path": "terminal/terminal.js", - "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b" + "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b", + "path": "terminal/terminal.js" }, { "size": 1261, - "path": "terminal/xterm-LICENSE.txt", - "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd" + "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", + "path": "terminal/xterm-LICENSE.txt" }, { "size": 7112, - "path": "terminal/xterm.css", - "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6" + "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", + "path": "terminal/xterm.css" }, { "size": 488663, - "path": "terminal/xterm.js", - "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972" + "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", + "path": "terminal/xterm.js" }, { "size": 4401, - "path": "LICENSE", - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", + "path": "LICENSE" }, { "size": 1096, - "path": "json-LICENSE.txt", - "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831" + "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", + "path": "json-LICENSE.txt" }, { "size": 883, - "path": "files-text-license.txt", - "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625" + "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", + "path": "files-text-license.txt" }, { "size": 95524, - "path": "README.md", - "sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6" + "sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6", + "path": "README.md" }, { - "size": 11906, - "path": "LAN-PREVIEW.md", - "sha256": "c1ee730c9b42b63f9501eaeb3fa4b5f16af17953615e526c53b76ac4fb7541bf" + "size": 12353, + "sha256": "3ab51025826e8aa2f7c07b70b920b556409b002029b4bb92cb34c5b32dac6e54", + "path": "LAN-PREVIEW.md" }, { "size": 732485, - "path": "dictionaries/en.txt", - "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9" + "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", + "path": "dictionaries/en.txt" }, { "size": 20566, - "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", - "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5" + "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", + "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt" }, { "size": 2265, - "path": "dictionaries/README.md", - "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311" + "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", + "path": "dictionaries/README.md" }, { "size": 1109134, - "path": "dictionaries/ru.txt", - "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849" + "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", + "path": "dictionaries/ru.txt" }, { "size": 1280, - "path": "dictionaries/sources.json", - "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408" + "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", + "path": "dictionaries/sources.json" }, { "size": 940799, - "path": "dictionaries/uk.txt", - "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf" + "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", + "path": "dictionaries/uk.txt" }, { "size": 993, - "path": "tools/README.txt", - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", + "path": "tools/README.txt" }, { "size": 540583, - "path": "tools/StayHere.exe", - "sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c" + "sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c", + "path": "tools/StayHere.exe" }, { "size": 2796, - "path": "tools/StayHere-README.md", - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", + "path": "tools/StayHere-README.md" } ] } diff --git a/resources/app.rc b/resources/app.rc index de14dc3..25ac656 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,122,0 - PRODUCTVERSION 0,6,122,0 + FILEVERSION 0,6,123,0 + PRODUCTVERSION 0,6,123,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.122" + VALUE "FileVersion", "0.6.123" END END BLOCK "VarFileInfo" diff --git a/src/app.cpp b/src/app.cpp index 25cd208..be3e872 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -953,17 +953,21 @@ bool App::updateTray(DWORD action, bool notifyFile) auto tip = localBuildTitle(L"KSwitcher"); if (trayInput.paired) { - const bool connected = trayInput.connected == trayInput.paired; - const uint32_t color = trayInput.stopped ? 0xfff16b66 : connected ? 0xff45d58c : - trayInputPulse ? 0xffffc457 : 0xffac7830; + const bool reconnecting = trayInput.reconnecting(); + const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab : + !reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830; badge = trayInputIcon(icon.hIcon, width, height, color); if (badge) icon.hIcon = badge; tip += L" — Mouse & keyboard: "; if (trayInput.stopped) tip += L"connection stopped"; - else if (connected) tip += L"connected"; + else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery."; else - tip += L"reconnecting (" + std::to_wstring(trayInput.connected) + L"/" + - std::to_wstring(trayInput.paired) + L" PCs connected)"; + { + tip += reconnecting ? L"reconnecting" : L"connected"; + if (trayInput.connected < trayInput.paired) + tip += L" (" + std::to_wstring(trayInput.connected) + L"/" + + std::to_wstring(trayInput.paired) + L" PCs connected)"; + } } else if (!incomingLanFileCount) tip = localBuildTitle(L"KSwitcher — keyboard layouts & clipboard"); @@ -988,7 +992,7 @@ void App::refreshTrayInput() if (state == trayInput) return; trayInput = state; trayInputPulse = true; - if (state.connected < state.paired && !state.stopped) + if (state.reconnecting()) SetTimer(window, TrayInputTimer, TrayInputPulseMs, nullptr); else KillTimer(window, TrayInputTimer); @@ -3402,7 +3406,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) } if (wp == TrayInputTimer) { - if (app->trayInput.connected < app->trayInput.paired && !app->trayInput.stopped) + if (app->trayInput.reconnecting()) { app->trayInputPulse = !app->trayInputPulse; app->updateTray(NIM_MODIFY); diff --git a/src/lan.cpp b/src/lan.cpp index bd94f8f..38610ee 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -110,7 +110,14 @@ void lan::wakeFilesPeer(const std::string &id) struct LanService::Impl { - struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; }; + struct Peer + { + std::string name,epoch; + sockaddr_in address{}; + uint64_t seen{},verified{}; + bool files{}; + bool present(uint64_t now)const{return verified && now-verified peers; @@ -139,7 +146,7 @@ struct LanService::Impl std::map inputReady; std::unique_ptr router; std::string inputStatus="Input sharing disabled."; - size_t inputConnectedPeers{}; + size_t inputConnectedPeers{}, inputOnlinePeers{}; bool inputWorkerStopped{}; bool inputNeedsHelp{}; HWND inputWindow{};std::atomic inputNotification{false}; @@ -214,7 +221,7 @@ struct LanService::Impl void start() { stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers..."; - updateInputStatus(0,"Connecting input channels...",false); + updateInputStatus(0,0,"Waiting for paired computers...",false); worker=std::thread([this]{ run(); }); } void stop() @@ -226,13 +233,14 @@ struct LanService::Impl transfers=std::make_unique(id,"file-transfer");incomingFiles.clear();logDownload.reset(); if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE); } - void updateInputStatus(size_t connected,std::string status,bool needsHelp,bool stopped=false) + void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false) { bool changed; { std::lock_guard lock(mutex); - changed=connected!=inputConnectedPeers||stopped!=inputWorkerStopped; + changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped; inputConnectedPeers=connected; + inputOnlinePeers=online; inputWorkerStopped=stopped; inputStatus=std::move(status); inputNeedsHelp=needsHelp; @@ -244,6 +252,16 @@ struct LanService::Impl auto bytes=j.dump(); if(bytes.size()>2048) return; sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address)); } + Json discoveryAnnouncement(bool filesListening)const + { + auto hello=lan::envelope("hello",id); + hello["name"]=name; + hello["epoch"]=epoch; + hello["clipboardSession"]=clipboard->session(); + hello["fileSession"]=transfers->session(); + hello["filesBrowse"]=filesListening; + return hello; + } std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b) { return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; } void receiveTransfers(uint64_t now) @@ -281,7 +299,7 @@ struct LanService::Impl } transfers->deliveries.clear(); } - void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now) + void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening) { if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return; auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return; @@ -292,19 +310,23 @@ struct LanService::Impl if(display.empty()||display.size()>128||!lan::identifier(session)|| std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return; // Discovery is untrusted and never grants input access. - if(!peers.contains(other) && peers.size()>=64) return; + const bool firstAnnouncement=!peers.contains(other); + if(firstAnnouncement && peers.size()>=64) return; auto &peer=peers[other]; // A fresh announcement rotates the challenge every three seconds; it // does not revoke a recent successful proof for the same address. // Only a valid presence response renews verified, so untrusted/replayed // announcements cannot extend its PeerLifetime expiry. - if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0; + const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr; + if(addressChanged) peer.verified=0; clipboard->peerSession(other,j.value("clipboardSession","")); transfers->peerSession(other,j.value("fileSession","")); peer.files=j.value("filesBrowse",false); peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now; if(trusted.contains(other)) { + // A returning peer can prove presence right away using our current challenge. + if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening)); auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch; const auto &key=trusted[other].at("key"); const auto challenge=heartbeat(id,other,epoch,session); @@ -423,13 +445,16 @@ struct LanService::Impl }); clipboardActive=clipboard->active()||transfers->active(); if(shareInput)for(auto &[peer,entry]:trusted.items()) - endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0}); + { + const auto found=peers.find(peer); + const bool discovered=found!=peers.end()&&found->second.present(now); + endpoints.push_back({.id=peer,.key=entry.at("key"), + .address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered}); + } if(refreshFiles.exchange(false) || now>=nextHello) { epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online. - auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session(); - hello["fileSession"]=transfers->session(); - hello["filesBrowse"]=filesListening; + const auto hello=discoveryAnnouncement(filesListening); for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); } nextHello=now+3000; } @@ -461,8 +486,10 @@ struct LanService::Impl } if(!in.empty()&&inputWindow&&!inputNotification.exchange(true)) if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false; - updateInputStatus(connected,hub.status(),hub.needsHelp()); - fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000}; + const auto online=hub.onlinePeers(); + updateInputStatus(connected,online,online||endpoints.empty()?hub.status(): + "All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp()); + fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000}; int ready=select(0,&read,nullptr,nullptr,&delay); if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed."); if(ready>0) for(int count=0;count<64;++count) @@ -477,7 +504,7 @@ struct LanService::Impl bool allowed=false;auto peer=j.value("id",""); {std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;} if(allowed)hub.receiveDatagram(j,GetTickCount64()); - }else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());} + }else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);} } catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery. } @@ -486,7 +513,7 @@ struct LanService::Impl catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); } {std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();} ++inputEpoch; - updateInputStatus(0,"Input connection closed.",false,true); + updateInputStatus(0,0,"Input connection closed.",false,true); if(socket!=INVALID_SOCKET) closesocket(socket); if(winsock) WSACleanup(); } @@ -518,8 +545,7 @@ struct LanService::Impl { auto peer=j.at("peer").get(); const auto checkPeer = [&] { - if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified|| - now-peers.at(peer).verified>=lan::PeerLifetime) + if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now)) throw std::runtime_error("Select an online paired computer."); if(!transfers->hasSession(peer)) throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers."); @@ -664,7 +690,7 @@ struct LanService::Impl if(action=="filesPeers" && !trusted.contains(peer)) continue; char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip)); result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)}, - {"verified",p.verified && now-p.verifiedhasSession(peer)},{"filesBrowse",p.files}}); } for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer)) @@ -702,7 +728,7 @@ LanInputConnections LanService::inputConnections()const std::lock_guard lock(impl->mutex); if(!inputEnabled())return {}; const auto paired=impl->trusted.size(); - return {std::min(impl->inputConnectedPeers,paired),paired,impl->inputWorkerStopped}; + return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped}; } bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);} bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());} diff --git a/src/lan.h b/src/lan.h index bd1b7fa..babea44 100644 --- a/src/lan.h +++ b/src/lan.h @@ -11,8 +11,9 @@ inline constexpr UINT LanInputStatusMessage=WM_APP+91; struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};}; struct LanInputConnections { - size_t connected{}, paired{}; + size_t connected{}, online{}, paired{}; bool stopped{}; + bool reconnecting()const{return !stopped&&connectedreset(GetTickCount64(),"Input disconnected std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";} struct InputHub::Impl { - struct Link { InputEndpoint endpoint;std::unique_ptr channel;std::unique_ptr udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; }; + struct Link + { + InputEndpoint endpoint; + std::unique_ptr channel; + std::unique_ptr udp; + uint64_t generation{},epoch{},since{},failedSince{}; + bool udpReady{}; + std::string lastState; + bool ready()const{return channel->ready()||udp->ready();} + }; struct Pending {SOCKET socket;uint32_t address;uint64_t since;}; std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET; std::map links;std::vector pending;uint64_t epoch{},retry{}; @@ -236,17 +245,18 @@ struct InputHub::Impl currentTime=now; for(auto it=links.begin();it!=links.end();){ auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;}); - if(match==endpoints.end())it=links.erase(it);else ++it; + // Discovery gates new attempts. An authenticated connection can outlive discovery. + if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it; } - for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){ + for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){ Link link;link.endpoint=e;link.channel=std::make_unique(local,e.id,e.key,0,e.port,true); link.udp=std::make_unique(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link)); } // Discovery is a hint, not the lifetime of authenticated input sessions. // Keep the last usable address across missed announcements. A new address // is used only once a channel is down, never to tear down working input. - for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id); - if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){ + for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id); + if(e.address&&!link.ready()&&e.address!=link.endpoint.address){ link.channel->disconnect();link.endpoint.address=e.address; } } @@ -289,8 +299,7 @@ struct InputHub::Impl if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();} }else link.channel->poll(link.endpoint.address,frames,received,now); if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;} - bool ready=link.channel->ready()||link.udp->ready(); - if(ready)link.failedSince=link.since=now; + if(link.ready())link.failedSince=link.since=now; auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status(); if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));} if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;} @@ -301,7 +310,8 @@ struct InputHub::Impl InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique(std::move(id),port)){} InputHub::~InputHub()=default; void InputHub::poll(const std::vector &peers,const std::vector &out,std::vector &in,uint64_t now){impl->poll(peers,out,in,now);} -std::map InputHub::ready()const{std::map result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;} +std::map InputHub::ready()const{std::map result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;} +size_t InputHub::onlinePeers()const{return impl->links.size();} std::string InputHub::status()const{ auto count=ready().size();if(count==impl->links.size()&&count){ std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());} @@ -309,7 +319,7 @@ std::string InputHub::status()const{ } if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands."; if(!impl->error.empty())return impl->error; - for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState; + for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState; return "Waiting for paired computers..."; } void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}} @@ -322,7 +332,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){ if(!active&&link.udp->active())link.channel->disconnect(); } bool InputHub::needsHelp()const{ - for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true; + for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true; return false; } } diff --git a/src/lan_channel.h b/src/lan_channel.h index 463bb90..362f460 100644 --- a/src/lan_channel.h +++ b/src/lan_channel.h @@ -61,7 +61,13 @@ class InputChannel void disconnect(); std::string transport()const; }; -struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;}; +struct InputEndpoint +{ + std::string id,key; + uint32_t address{}; + uint16_t port=45884; + bool discovered=true; +}; struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};}; class InputHub { @@ -71,6 +77,7 @@ class InputHub ~InputHub(); void poll(const std::vector &,const std::vector &,std::vector &,uint64_t now); std::map ready()const; + size_t onlinePeers()const; std::string status()const; void disconnect(); using SendDatagram=std::function; diff --git a/src/update.h b/src/update.h index f9f847a..96d3b74 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.122"; +inline constexpr wchar_t AppVersion[] = L"0.6.123"; 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_input.cpp b/tests/lan_input.cpp index 4d3eeec..be10bfa 100644 --- a/tests/lan_input.cpp +++ b/tests/lan_input.cpp @@ -319,10 +319,10 @@ void hubChecks() while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()ready().size()==2&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"three TCP hubs authenticate all independent pair channels on one listener per PC"); auto generation=hubs[0]->ready(); - for(auto &list:endpoints)for(auto &e:list)e.address=0; + for(auto &list:endpoints)for(auto &e:list){e.address=0;e.discovered=false;} for(int n=0;n<20;++n)pump(); check(hubs[0]->ready()==generation&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"expired discovery does not destroy authenticated channels"); - for(auto &list:endpoints)for(auto &e:list)e.address=htonl(INADDR_LOOPBACK); + for(auto &list:endpoints)for(auto &e:list){e.address=htonl(INADDR_LOOPBACK);e.discovered=true;} InputFrame keyFrame{InputType::Key,7,'A',0,1},cross{InputType::Cross,8,2,30000}; hubs[0]->poll(endpoints[0],{{ids[1],keyFrame},{ids[2],cross}},incoming[0],GetTickCount64()); for(int n=0;n<100&&(incoming[1].empty()||incoming[2].empty());++n)pump(); @@ -340,11 +340,50 @@ void hubChecks() for(int n=0;n<300&&(server.ready().empty()||client.ready().empty());++n){ server.poll(unknown,{},a,GetTickCount64());client.poll(known,{},b,GetTickCount64());Sleep(1); } - check(server.ready().size()==1&&client.ready().size()==1,"saved pair listens and authenticates without receiving a discovery announcement"); + check(server.ready().size()==1&&client.ready().size()==1,"available peer can accept inbound TCP without dialing"); } endpoints[0].erase(endpoints[0].begin());hubs[0]->poll(endpoints[0],{},incoming[0],GetTickCount64()+1800); check(!hubs[0]->ready().contains(ids[1])&&hubs[0]->ready().contains(ids[2]),"forgetting one pair revokes only its channel"); } +void offlineDiscoveryChecks() +{ + WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup"); + struct Close{~Close(){WSACleanup();}} close; + std::string a(32,'a'),b(32,'b'),key(64,'f'); + const auto pa=freePort(),pb=freePort(); + InputHub left(a,pa),right(b,pb); + std::vector ea{{b,key,htonl(INADDR_LOOPBACK),pb,false}},eb{{a,key,htonl(INADDR_LOOPBACK),pa,false}}; + std::vector ia,ib; + int datagrams=0; + left.datagrams([&](const auto &,const auto &){++datagrams;}); + auto now=GetTickCount64(); + auto pump=[&](uint64_t step=1){now+=step;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);}; + auto checkIdle=[&]{ + check(left.onlinePeers()==0&&left.ready().empty()&&!left.needsHelp()&&datagrams==0, + "offline saved peer does not trigger input retries or connection help"); + SOCKET probe=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); + sockaddr_in addr{};addr.sin_family=AF_INET;addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);addr.sin_port=htons(pa); + int result=connect(probe,(sockaddr*)&addr,sizeof(addr)); + const auto error=WSAGetLastError();closesocket(probe); + check(result==SOCKET_ERROR&&error==WSAECONNREFUSED,"input TCP listener is closed while all peers are offline"); + }; + pump();pump(20000);checkIdle(); + auto rediscover=[&]{ + ea.front().discovered=eb.front().discovered=true; + for(int n=0;n<200&&(left.ready().empty()||right.ready().empty());++n){pump(20);Sleep(1);} + check(left.onlinePeers()==1&&left.ready().contains(b)&&right.ready().contains(a), + "input TCP connects when the saved peer reappears in discovery"); + }; + rediscover(); + const auto oldEpoch=left.ready().at(b); + ea.front().discovered=false; + eb.clear(); // The other instance stops while discovery is already stale. + for(int n=0;n<30;++n){pump(20);Sleep(1);} + pump(20000);checkIdle(); + eb={{a,key,htonl(INADDR_LOOPBACK),pa,false}}; + rediscover(); + check(left.ready().at(b)!=oldEpoch,"rediscovery replaces the disconnected input generation"); +} void fallbackChecks() { WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup"); @@ -528,6 +567,6 @@ void channelChecks() } int main() { - try{channelChecks();hubChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<