Add opt-in KSwitcher LAN discovery and mutual code pairing preview

This commit is contained in:
agrynco committed 2026-11-06 15:30:06 +02:00
1 parent 346af2256f
commit 9b565dd55e
17 files changed
+743 -21

No files matched your search

+228
View File
@@ -0,0 +1,228 @@
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include "lan.h"
#include "lan_pairing.h"
#include <atomic>
#include <mutex>
#include <thread>
#include <map>
namespace ks
{
using lan::Json;
namespace
{
Bytes encoded(const Json &j) { auto s=j.dump(); return Bytes(s.begin(),s.end()); }
bool localAddress(ULONG network)
{
auto ip=ntohl(network);
return (ip>>24)==10 || (ip>>20)==0xac1 || (ip>>16)==0xc0a8 || (ip>>16)==0xa9fe;
}
std::string hostName()
{
wchar_t name[256]{}; DWORD size=256;
return GetComputerNameW(name,&size) ? utf8(std::wstring(name,size)) : "KSwitcher";
}
std::vector<ULONG> broadcasts()
{
ULONG size=16384; Bytes data(size);
auto flags=GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER;
auto result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size);
if(result==ERROR_BUFFER_OVERFLOW) { data.resize(size); result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size); }
std::vector<ULONG> out;
if(result!=NO_ERROR) return out;
for(auto a=(IP_ADAPTER_ADDRESSES*)data.data();a;a=a->Next)
if(a->OperStatus==IfOperStatusUp)
for(auto u=a->FirstUnicastAddress;u;u=u->Next)
if(u->Address.lpSockaddr->sa_family==AF_INET && u->OnLinkPrefixLength>0 && u->OnLinkPrefixLength<31)
{
auto ip=((sockaddr_in*)u->Address.lpSockaddr)->sin_addr.s_addr;
if(localAddress(ip)) out.push_back(htonl(ntohl(ip) | (0xffffffffu >> u->OnLinkPrefixLength)));
}
return out;
}
}
struct LanService::Impl
{
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; };
std::filesystem::path path;
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
std::map<std::string,Peer> peers;
Json trusted=Json::object();
std::unique_ptr<lan::Pairing> pending;
bool enabled{};
std::atomic<bool> stopping{false};
std::mutex mutex;
std::thread worker;
explicit Impl(const std::filesystem::path &root) : path(root/L"lan-pairing.bin")
{
if(std::filesystem::exists(path))
{
auto j=Json::parse(unprotect(readFile(path,256*1024)));
if(j.value("version",0)!=1 || !lan::identifier(j.value("id",""))) throw std::runtime_error("Invalid local LAN configuration.");
id=j.at("id"); enabled=j.value("enabled",false); trusted=j.at("trusted");
if(!trusted.is_object()||trusted.size()>64) throw std::runtime_error("Invalid paired computer list.");
for(auto &[key,entry]:trusted.items())
if(!lan::identifier(key)||key==id||entry.at("key").get<std::string>().size()!=64||
!entry.at("name").is_string()||entry.at("name").get<std::string>().size()>128)
throw std::runtime_error("Invalid paired computer key.");
}
else id=lan::randomHex(16);
if(enabled) start();
}
~Impl() { stop(); }
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted}}))); }
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
worker=std::thread([this]{ run(); });
}
void stop()
{
stopping=true;
if(worker.joinable()) worker.join();
std::lock_guard lock(mutex); pending.reset(); peers.clear();
}
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));
}
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 receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
{
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
auto type=j.value("type","");
if(type=="hello")
{
auto display=j.value("name",""); auto session=j.value("epoch","");
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;
auto &peer=peers[other];
if(peer.epoch!=session || peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
if(trusted.contains(other))
{
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
response["proof"]=lan::mac(trusted[other].at("key"),heartbeat(id,other,epoch,session));
send(socket,address,response);
}
return;
}
if(!peers.contains(other)||j.value("to","")!=id) return;
auto &peer=peers.at(other);
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) return;
if(type=="presence" && trusted.contains(other) && j.value("epoch","")==peer.epoch &&
lan::equal(j.value("proof",""),lan::mac(trusted[other].at("key"),heartbeat(other,id,peer.epoch,epoch))))
{ peer.verified=now; return; }
if(pending && pending->peer==other)
{
for(const auto &response:pending->receive(j,now)) send(socket,address,response);
if(pending->confirmed && (!trusted.contains(other)||trusted[other].at("key")!=pending->derived))
{
auto previous=trusted;
trusted[other]={{"name",peer.name},{"key",pending->derived}};
try {save();} catch(...) {trusted=std::move(previous);throw;}
peer.verified=now; status="Paired. Input and clipboard sharing are not enabled in this preview.";
}
}
}
void run() noexcept
{
WSADATA startup{}; SOCKET socket=INVALID_SOCKET; bool winsock=false;
try
{
if(WSAStartup(MAKEWORD(2,2),&startup)) throw std::runtime_error("Cannot start Windows networking.");
winsock=true; socket=::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
BOOL yes=TRUE; u_long nonblock=1;
if(socket==INVALID_SOCKET || setsockopt(socket,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,(char*)&yes,sizeof(yes)) ||
setsockopt(socket,SOL_SOCKET,SO_BROADCAST,(char*)&yes,sizeof(yes)) || ioctlsocket(socket,FIONBIO,&nonblock))
throw std::runtime_error("Cannot open LAN discovery socket.");
sockaddr_in bound{}; bound.sin_family=AF_INET; bound.sin_port=htons(lan::Port);
if(bind(socket,(sockaddr*)&bound,sizeof(bound))) throw std::runtime_error("UDP port 45883 is in use. Only one LAN-enabled KSwitcher may run per computer.");
uint64_t nextHello=0,nextOffer=0;
while(!stopping)
{
auto now=GetTickCount64();
{
std::lock_guard lock(mutex);
if(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;
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
nextHello=now+3000;
}
for(auto it=peers.begin();it!=peers.end();) {
if(now-it->second.seen>lan::PeerLifetime) it=peers.erase(it); else ++it;
}
if(pending && pending->expired(now)) {
status=pending->confirmed ? "Pair saved. Select a computer to manage it." : "Pairing expired. Enter the same code and click Pair on both computers.";
pending.reset();
}
if(pending && now>=nextOffer && peers.contains(pending->peer)) {
send(socket,peers.at(pending->peer).address,pending->offer()); nextOffer=now+1000;
}
}
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,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)
{
char buffer[2049]; sockaddr_in sender{}; int size=sizeof(sender);
int received=recvfrom(socket,buffer,sizeof(buffer),0,(sockaddr*)&sender,&size);
if(received<=0) break;
if(received>2048||sender.sin_port!=htons(lan::Port)||!localAddress(sender.sin_addr.s_addr)) continue;
try { auto j=Json::parse(buffer,buffer+received); std::lock_guard lock(mutex); receive(socket,sender,j,GetTickCount64()); }
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(); }
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
Bytes command(const Bytes &input)
{
auto j=Json::parse(input); auto action=j.value("action","status");
if(action=="enable")
{
stop();
bool previous=enabled; enabled=j.at("enabled").get<bool>();
try {save();} catch(...) {enabled=previous;if(enabled) start();throw;}
if(enabled) start(); else status="Disabled. No discovery sockets or worker thread.";
}
std::lock_guard lock(mutex);
if(action=="code") return encoded({{"code",lan::randomHex(16)}});
if(action=="cancel") { pending.reset(); status="Pairing cancelled."; }
if(action=="pair")
{
auto peer=j.at("peer").get<std::string>();
if(!enabled||!peers.contains(peer)) throw std::runtime_error("Select an available KSwitcher computer first.");
if(!trusted.contains(peer)&&trusted.size()>=64) throw std::runtime_error("Remove an old pair before adding another computer.");
pending=std::make_unique<lan::Pairing>(id,peer,j.at("code").get<std::string>(),GetTickCount64());
status="Waiting for the same code and Pair on the other KSwitcher (2 minutes)...";
}
if(action=="forget") { auto peer=j.at("peer").get<std::string>(); trusted.erase(peer); if(pending&&pending->peer==peer) pending.reset(); save(); status="Pair removed on this computer."; }
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()}};
auto now=GetTickCount64();
for(const auto &[peer,p]:peers)
{
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}});
}
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
result["peers"].push_back({{"id",peer},{"name",p.at("name")},{"address",""},{"paired",true},{"verified",false},{"online",false}});
return encoded(result);
}
};
LanService::LanService(const std::filesystem::path &path) : impl(std::make_unique<Impl>(path)) {}
LanService::~LanService()=default;
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
}