Compare commits

...
Author SHA1 Message Date
agrynco bdd058f493 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.
2026-11-20 20:40:01 +02:00
agrynco e7624b620e Release KSwitcher v0.6.122 (#68)
Ship LAN input reconnection and a tray connection indicator. Include the verified Windows x64 package manifest and checksum.
2026-11-20 18:44:21 +02:00
16 changed files with 434 additions and 144 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.121 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.123 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+14 -2
View File
@@ -59,6 +59,12 @@ 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 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.
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
@@ -105,8 +111,14 @@ 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.
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
encrypted UDP input session on the existing discovery socket (UDP 45883).
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.
UDP uses fresh session challenges, authenticated encryption, ordered event
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
key presses. Two seconds without authenticated traffic or acknowledgement
+20
View File
@@ -1,5 +1,25 @@
# 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.
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
**Українською.**
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
## v0.6.121 — 2026-11-20
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
+1 -1
View File
@@ -1 +1 @@
c7163b614f4e92e25137a3f89e750878fc9a3e559037e7a8933468b8b83d829d KSwitcher-win-x64.zip
868941978ca231f3df01917277d8ec5b8de970c81f6b83b5fa9e64b18b71ab9a KSwitcher-win-x64.zip
+71 -71
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.121",
"schema": 1,
"version": "0.6.123",
"files": [
{
"path": "KSwitcher.exe",
"size": 2479616,
"sha256": "fbdb81083b17c15d784f6772fea286d78a7e7b48ae16ca0216734631ba374fa7"
"size": 5892884,
"sha256": "043c10eb6752656fc2aa6c1f8d329d4fe243347a5275088e5dc4385638acd870",
"path": "KSwitcher.exe"
},
{
"path": "KSwitcher.Config.exe",
"size": 2457088,
"sha256": "d55ba3ffead5ef585d41e705388eb8f9282e74b8a3c603d0eaf37576e2072b6d"
"size": 5948997,
"sha256": "ac6368858b86d4e9a4a2c1cf4cd90c39b58d699909c417f73d9f882c54dd96a0",
"path": "KSwitcher.Config.exe"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3059200,
"sha256": "207f9cb7bd26c3eb1a2e71719aac0d503514af1754d18659934610a80f02a8da"
"size": 5763947,
"sha256": "d2f435c645419a155e6feac7761d9894f7bd2099cd695a93650847c869c50ffb",
"path": "KSwitcher.Screenshot.exe"
},
{
"path": "KSwitcher.Files.exe",
"size": 4370944,
"sha256": "54030d33097766cb9665ec0f5ab0967642d1bcdf3b9e151948ae5d85781dd1fe"
"size": 9395313,
"sha256": "43512aa25c8b9854cb3134b9480e24049eab77a0008af55cede06369dc6a0964",
"path": "KSwitcher.Files.exe"
},
{
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll"
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js"
},
{
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html"
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js"
},
{
"path": "terminal/markdown.html",
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094"
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"path": "terminal/markdown.html"
},
{
"path": "terminal/markdown.js",
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8"
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"path": "terminal/markdown.js"
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt"
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js"
},
{
"path": "terminal/terminal.js",
"size": 5065,
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"path": "terminal/terminal.js"
},
{
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt"
},
{
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css"
},
{
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js"
},
{
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE"
},
{
"path": "json-LICENSE.txt",
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt"
},
{
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
},
{
"path": "README.md",
"size": 95524,
"sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6"
"sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6",
"path": "README.md"
},
{
"path": "LAN-PREVIEW.md",
"size": 11577,
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"size": 12353,
"sha256": "3ab51025826e8aa2f7c07b70b920b556409b002029b4bb92cb34c5b32dac6e54",
"path": "LAN-PREVIEW.md"
},
{
"path": "dictionaries/en.txt",
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt"
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"path": "dictionaries/README.md",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md"
},
{
"path": "dictionaries/ru.txt",
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt"
},
{
"path": "dictionaries/sources.json",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json"
},
{
"path": "dictionaries/uk.txt",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt"
},
{
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt"
},
{
"path": "tools/StayHere.exe",
"size": 133120,
"sha256": "e23960ff3328f38c050528091ba78b822f0fa74e3396e1a349150e2947598d96"
"size": 540583,
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c",
"path": "tools/StayHere.exe"
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md"
}
]
}
+3 -3
View File
@@ -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,121,0
PRODUCTVERSION 0,6,121,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.121"
VALUE "FileVersion", "0.6.123"
END
END
BLOCK "VarFileInfo"
+126 -24
View File
@@ -889,30 +889,132 @@ void App::report(const std::wstring &text)
}
constexpr UINT_PTR TrayRetryTimer = 20;
constexpr UINT TrayRetryIntervalMs = 1000;
constexpr UINT_PTR TrayInputTimer = 22;
constexpr UINT TrayInputPulseMs = 450;
void App::addTray()
namespace
{
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
{
if (!base || width < 8 || height < 8) return nullptr;
BITMAPINFO bitmapInfo{};
bitmapInfo.bmiHeader = {sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB};
void *bits{};
HBITMAP bitmap = CreateDIBSection(nullptr, &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0);
if (!bitmap) return nullptr;
HDC dc = CreateCompatibleDC(nullptr);
HICON icon{};
if (dc)
{
auto previous = SelectObject(dc, bitmap);
auto pixels = static_cast<uint32_t *>(bits);
std::fill_n(pixels, size_t(width) * height, 0);
if (DrawIconEx(dc, 0, 0, base, width, height, 0, nullptr, DI_NORMAL))
{
GdiFlush();
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
const int cx = width - 1 - radius, cy = height - 1 - radius;
for (int y = -radius; y <= radius; ++y)
for (int x = -radius; x <= radius; ++x)
{
const int distance = x * x + y * y;
if (distance <= radius * radius)
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
? color : 0xff242424;
}
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
if (auto mask = CreateBitmap(width, height, 1, 1, maskBits.data()))
{
ICONINFO info{TRUE, 0, 0, mask, bitmap};
icon = CreateIconIndirect(&info);
DeleteObject(mask);
}
}
SelectObject(dc, previous);
DeleteDC(dc);
}
DeleteObject(bitmap);
return icon;
}
}
bool App::updateTray(DWORD action, bool notifyFile)
{
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;
icon.uFlags = NIF_ICON | NIF_TIP | NIF_SHOWTIP;
if (action == NIM_ADD) icon.uFlags |= NIF_MESSAGE;
icon.uCallbackMessage = TrayMessage;
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED);
auto tip = incomingLanFileCount ? L"KSwitcher — files ready to save: " + std::to_wstring(incomingLanFileCount)
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
const int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON, width, height, LR_SHARED);
HICON badge{};
auto tip = localBuildTitle(L"KSwitcher");
if (trayInput.paired)
{
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 (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery.";
else
{
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");
if (incomingLanFileCount)
tip += L"\nFiles ready to save: " + std::to_wstring(incomingLanFileCount);
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
if (Shell_NotifyIconW(NIM_ADD, &icon))
if (notifyFile)
{
icon.uFlags |= NIF_INFO;
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
icon.dwInfoFlags = NIIF_INFO;
}
const bool updated = Shell_NotifyIconW(action, &icon) != FALSE;
if (badge) DestroyIcon(badge);
return updated;
}
void App::refreshTrayInput()
{
const auto state = lanService ? lanService->inputConnections() : LanInputConnections{};
if (state == trayInput) return;
trayInput = state;
trayInputPulse = true;
if (state.reconnecting())
SetTimer(window, TrayInputTimer, TrayInputPulseMs, nullptr);
else
KillTimer(window, TrayInputTimer);
updateTray(NIM_MODIFY);
}
void App::addTray()
{
if (updateTray(NIM_ADD))
{
KillTimer(window, TrayRetryTimer);
trayRetryPending = false;
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &icon);
}
else if (!trayRetryPending)
{
trayRetryPending = SetTimer(window, TrayRetryTimer, TrayRetryIntervalMs, nullptr) != 0;
}
icon.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &icon);
}
bool App::registerHotkeys(const Settings &s, bool rollback)
{
@@ -953,6 +1055,7 @@ Bytes App::lanCommand(const Bytes &command)
if (lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
else KillTimer(window, 7);
if (lanService->takeInputChange()) resetLanInput();
refreshTrayInput();
return reply;
}
void App::applySettings(const Settings &requested)
@@ -3253,23 +3356,12 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case LanFilesChangedMessage:
{
app->incomingLanFileCount = wp;
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = hwnd;
icon.uID = 1;
icon.uFlags = NIF_TIP | NIF_SHOWTIP;
auto tip = wp ? L"KSwitcher — files ready to save: " + std::to_wstring(wp)
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
if (lp)
{
icon.uFlags |= NIF_INFO;
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
icon.dwInfoFlags = NIIF_INFO;
}
if (Shell_NotifyIconW(NIM_MODIFY, &icon) && lp) app->incomingFileBalloon = true;
if (app->updateTray(NIM_MODIFY, lp != 0) && lp) app->incomingFileBalloon = true;
return 0;
}
case LanInputStatusMessage:
app->refreshTrayInput();
return 0;
case CheckAutostartMessage:
app->checkAutostartPath();
return 0;
@@ -3312,6 +3404,15 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
if (app->trayRetryPending) app->addTray();
return 0;
}
if (wp == TrayInputTimer)
{
if (app->trayInput.reconnecting())
{
app->trayInputPulse = !app->trayInputPulse;
app->updateTray(NIM_MODIFY);
}
return 0;
}
if (wp == MouseClickTimer) { app->flushMouseClicks(); return 0; }
if (wp >= FirstMouseVolumeTimer && wp < FirstMouseVolumeTimer + std::size(MouseButtonNames))
{
@@ -3505,6 +3606,7 @@ int App::execute()
try { lanService = std::make_unique<LanService>(data,window); }
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
refreshTrayInput();
SetTimer(window, 1, 60000, nullptr);
if (!smoke) SetTimer(window, 6, 1000, nullptr);
if (!smoke) SetTimer(window, 8, 250, nullptr);
+4
View File
@@ -161,6 +161,10 @@ class App
bool stop{};
UINT taskbarCreated{};
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
bool updateTray(DWORD action, bool notifyFile = false);
void refreshTrayInput();
uint64_t transformAttempt{}, previousAttemptVersion{};
size_t incomingLanFileCount{};
bool incomingFileBalloon{};
+69 -21
View File
@@ -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<lan::PeerLifetime;}
};
std::filesystem::path path;
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
std::map<std::string,Peer> peers;
@@ -129,7 +136,7 @@ struct LanService::Impl
bool shareInput{};
std::string inputPeer;
int inputEdge=1;
std::atomic<bool> inputConnected{false},abortInput{false};
std::atomic<bool> abortInput{false};
std::atomic<uint64_t> inputEpoch{0};
std::atomic<uint64_t> inputConfiguration{0};
std::atomic<bool> layoutChanged{false};
@@ -139,6 +146,8 @@ struct LanService::Impl
std::map<std::string,uint64_t> inputReady;
std::unique_ptr<lan::InputMesh> router;
std::string inputStatus="Input sharing disabled.";
size_t inputConnectedPeers{}, inputOnlinePeers{};
bool inputWorkerStopped{};
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
@@ -212,6 +221,7 @@ struct LanService::Impl
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
updateInputStatus(0,0,"Waiting for paired computers...",false);
worker=std::thread([this]{ run(); });
}
void stop()
@@ -219,17 +229,39 @@ struct LanService::Impl
if(router)router->cancel(GetTickCount64());
stopping=true;
if(worker.joinable()) worker.join();
inputConnected=false;++inputEpoch;
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,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||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
inputConnectedPeers=connected;
inputOnlinePeers=online;
inputWorkerStopped=stopped;
inputStatus=std::move(status);
inputNeedsHelp=needsHelp;
}
if(changed&&inputWindow)PostMessageW(inputWindow,LanInputStatusMessage,0,0);
}
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
{
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)
@@ -267,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;
@@ -278,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);
@@ -409,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;
}
@@ -434,7 +473,7 @@ struct LanService::Impl
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
hub.poll(endpoints,out,in,now);
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
auto readyPeers=hub.ready();const auto connected=readyPeers.size();
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
for(auto &frame:in){
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
@@ -447,8 +486,10 @@ struct LanService::Impl
}
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
{std::lock_guard lock(mutex);inputStatus=hub.status();inputNeedsHelp=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)
@@ -463,15 +504,16 @@ 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.
}
}
}
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
inputConnected=false;++inputEpoch;
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
++inputEpoch;
updateInputStatus(0,0,"Input connection closed.",false,true);
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
@@ -503,8 +545,7 @@ struct LanService::Impl
{
auto peer=j.at("peer").get<std::string>();
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.");
@@ -628,7 +669,7 @@ struct LanService::Impl
status="Pair removed on this computer.";
}
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
result["shareLogs"]=shareLogs;
@@ -649,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.verified<lan::PeerLifetime},{"online",true},
{"verified",p.present(now)},{"online",true},
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
}
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
@@ -682,6 +723,13 @@ std::vector<LanClipboard> LanService::takeClipboard()
impl->clipboard->deliveries.clear();return result;
}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
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),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());}
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
+9
View File
@@ -7,7 +7,15 @@ 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;
inline constexpr UINT LanInputStatusMessage=WM_APP+91;
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
struct LanInputConnections
{
size_t connected{}, online{}, paired{};
bool stopped{};
bool reconnecting()const{return !stopped&&connected<online;}
bool operator==(const LanInputConnections &) const = default;
};
// Discovery, pairing and optional encrypted input within the resident process.
class LanService
{
@@ -21,6 +29,7 @@ class LanService
void publishClipboard(Bytes, const std::string &);
std::vector<LanClipboard> takeClipboard();
bool inputEnabled() const;
LanInputConnections inputConnections() const;
bool tickInput(bool allowEnter = true);
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
+25 -11
View File
@@ -213,6 +213,7 @@ bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
}
bool InputChannel::ready()const{return impl->authenticated;}
bool InputChannel::handshaking()const{return impl->socket!=INVALID_SOCKET&&!impl->authenticated;}
uint64_t InputChannel::generation()const{return impl->changed;}
std::string InputChannel::status()const{
return impl->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
@@ -221,7 +222,16 @@ void InputChannel::disconnect(){impl->reset(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<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
struct Link
{
InputEndpoint endpoint;
std::unique_ptr<InputChannel> channel;
std::unique_ptr<InputDatagram> 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<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
@@ -235,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<InputChannel>(local,e.id,e.key,0,e.port,true);
link.udp=std::make_unique<InputDatagram>(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;
}
}
@@ -279,14 +290,16 @@ struct InputHub::Impl
}
for(auto &[id,link]:links){
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
// Let an in-flight TCP connection finish or hit its own deadline.
// Check before poll() so another TCP retry cannot starve UDP fallback.
if(sendDatagram&&!link.channel->ready()&&!link.channel->handshaking()&&
!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);frames.clear();}
if(link.udp->active()){
link.udp->poll(frames,received,now,sendDatagram);
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;}
@@ -297,7 +310,8 @@ struct InputHub::Impl
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
InputHub::~InputHub()=default;
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> 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());}
@@ -305,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;}}
@@ -318,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;
}
}
+9 -1
View File
@@ -55,12 +55,19 @@ class InputChannel
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
bool adopt(uintptr_t socket,uint64_t now);
bool ready() const;
bool handshaking() const;
uint64_t generation() const;
std::string status() const;
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
{
@@ -70,6 +77,7 @@ class InputHub
~InputHub();
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
std::map<std::string,uint64_t> ready()const;
size_t onlinePeers()const;
std::string status()const;
void disconnect();
using SendDatagram=std::function<void(const std::string &,const Json &)>;
+16 -4
View File
@@ -211,9 +211,18 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
if(!connected||!env.desktop()){cancel(now);return;}
if(f.type==InputType::Enter)
{
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
{post({InputType::Return,f.token,32768});return;}
const wchar_t *declined=nullptr;
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
declined=L"invalid edge or position";
else if(held())declined=L"a local key or mouse button is held";
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
(mode_==ControlMode::Requesting&&preferLocal))
declined=L"another handoff is active";
if(declined)
{
log(std::wstring(L"LAN input: declined cursor handoff: ")+declined);
post({InputType::Return,f.token,32768});return;
}
if(mode_==ControlMode::Requesting)cancel(now);
if(multi)edge=f.a^1;
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
@@ -231,7 +240,10 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
return;
}
if(f.token!=token||!token)return;
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
if(f.type==InputType::Return){
log(mode_==ControlMode::Requesting?L"LAN input: peer declined cursor handoff":L"LAN input: peer returned control");
local(now,std::clamp(f.a,0,65535));return;
}
if(mode_!=ControlMode::Receiving)return;
bool ok=true;
if(f.type==InputType::Move)
+1
View File
@@ -50,6 +50,7 @@ class InputMesh
if(!ready.contains(peer)||!positions.contains(peer))return;
if(f.type==InputType::Enter){
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
send(peer,{InputType::Return,f.token,32768});return;
}
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.121";
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;
+64 -4
View File
@@ -319,10 +319,10 @@ void hubChecks()
while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()<deadline)pump();
check(hubs[0]->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,16 +340,76 @@ 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<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb,false}},eb{{a,key,htonl(INADDR_LOOPBACK),pa,false}};
std::vector<RoutedInput> 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");
struct Close{~Close(){WSACleanup();}} close;
std::string a(32,'a'),b(32,'b'),key(64,'f');
{
auto pa=freePort(),pb=freePort();InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb}},eb{{a,key,0}};
std::vector<RoutedInput> ia,ib;
int datagrams=0;
left.datagrams([&](const auto &,const auto &){++datagrams;});
auto now=GetTickCount64();
right.poll(eb,{},ib,now); // Listen, but delay reading and authenticating the TCP connection.
left.poll(ea,{},ia,now);
for(int n=0;n<100&&left.status().find("authenticating")==std::string::npos;++n){
Sleep(1);left.poll(ea,{},ia,now+1);
}
check(left.status().find("authenticating")!=std::string::npos,"TCP connection is waiting for the peer handshake");
now+=6000;
left.poll(ea,{},ia,now);
for(int n=0;n<100&&(left.ready().empty()||right.ready().empty());++n){
++now;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);Sleep(1);
}
check(left.ready().contains(b)&&right.ready().contains(a)&&datagrams==0,
"UDP fallback does not cancel a TCP handshake within its deadline");
}
for(bool udp:{false,true}){
auto pa=freePort(),pb=freePort(),blocked=freePort();InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),blocked}},eb{{a,key,htonl(INADDR_LOOPBACK),udp?blocked:pa}};
@@ -507,6 +567,6 @@ void channelChecks()
}
int main()
{
try{channelChecks();hubChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
}