#include #include #include "lan_files.h" #include "files_lan_ipc.h" #include #include #include #include #include using namespace ks; using namespace ks::lan; namespace fs=std::filesystem; namespace { void require(bool condition,const char *message) { if(!condition) throw std::runtime_error(message); } void verifyFilesPeerImage() { const fs::path install = LR"(C:\Tools\KSwitcher)"; const auto transaction = install / L".kswitcher-update-0123456789abcdef0123456789abcdef"; constexpr auto files = L"KSwitcher.Files.exe"; require(isFilesPeerImage(install / files, install), "installed Files can request LAN peers"); require(isFilesPeerImage(transaction / L"backup" / files, install), "Files open during an update can still request LAN peers"); require(!isFilesPeerImage(transaction / L"stage" / files, install), "staged Files image is rejected"); require(!isFilesPeerImage(transaction / L"backup" / L"KSwitcher.Config.exe", install), "another executable in the backup is rejected"); require(!isFilesPeerImage(install / L".kswitcher-update-invalid" / L"backup" / files, install), "malformed transaction directory is rejected"); require(!isFilesPeerImage(install.parent_path() / transaction.filename() / L"backup" / files, install), "backup outside the active installation is rejected"); } void save(const fs::path &path,const std::string &text) { std::ofstream file(path,std::ios::binary|std::ios::trunc); file.write(text.data(),text.size()); require(bool(file),"write test fixture"); } std::string load(const fs::path &path) { std::ifstream file(path,std::ios::binary); return {std::istreambuf_iterator(file),{}}; } void verifyDirection(const FilesPeer *sourcePeer,const FilesPeer *targetPeer, const std::string &id,const std::string &key,const fs::path &root) { auto connect=[&](const FilesPeer *peer) { return peer?std::make_unique(*peer,id,key):std::make_unique(); }; const auto sourcePath=root/L"source.bin"; const auto targetPath=root/L"target.bin"; std::string content(FileChunk*3+5,'a'); for(size_t i=0;i((i/257)%251); save(sourcePath,content); save(targetPath,"original"); auto source=connect(sourcePeer); const auto info=source->call(fileRequest("stat",sourcePath)); checkFileReply(info); const auto size=info.at("size").get(),modified=info.at("modified").get(); auto target=connect(targetPeer); try { streamFile(*source,*target,id,sourcePath,targetPath,size,modified,true,false, [](uint64_t done,uint64_t) { if(done==FileChunk) throw std::system_error(WSAECONNRESET,std::system_category()); return true; }); require(false,"interruption expected"); } catch(const std::system_error &e){require(e.code().value()==WSAECONNRESET,"unexpected transfer failure");} target.reset(); source.reset(); require(load(targetPath)=="original","interruption overwrote target"); require(load(sourcePath)==content,"interruption changed source"); fs::path partial; for(const auto &entry:fs::directory_iterator(root)) if(entry.path().extension()==L".partial") partial=entry.path(); require(!partial.empty() && fs::file_size(partial)==FileChunk,"confirmed chunk was lost"); source=connect(sourcePeer); target=connect(targetPeer); uint64_t offset=UINT64_MAX; streamFile(*source,*target,id,sourcePath,targetPath,size,modified,true,false, [&](uint64_t done,uint64_t){offset=std::min(offset,done);return true;}); require(offset==FileChunk,"resumed at the wrong offset"); require(load(targetPath)==content,"resumed file differs"); require(!fs::exists(partial),"committed partial remains"); require(load(sourcePath)==content,"copy removed source"); save(targetPath,"original"); try { streamFile(*source,*target,id,sourcePath,targetPath,size,modified,true,false, [](uint64_t done,uint64_t){return donecall(fileRequest("remove",sourcePath))); require(!fs::exists(sourcePath),"move source removal failed"); } } int main() { WSADATA network{}; if(WSAStartup(MAKEWORD(2,2),&network)) return 1; const auto root=fs::temp_directory_path()/wide("kswitcher-lan-files-"+randomHex(16)); int result=0; try { verifyFilesPeerImage(); fs::create_directory(root); const auto client=randomHex(16),first=randomHex(16),second=randomHex(16),key=randomHex(32); auto lookup=[&](const std::string &id){return id==client?key:std::string{};}; { auto previous=std::make_unique(first,lookup,0); const auto port=previous->port(); require(port!=0,"old listener bound before restart"); FilesListener restarting(first,lookup,port); require(restarting.port()==0,"new listener must not take over an occupied port"); previous.reset(); const auto deadline=GetTickCount64()+4000; while(!restarting.port() && GetTickCount64() allowTerminal{}; std::atomic hibernateRequests{}; std::atomic updateRequests{}; FilesListener a(first,lookup,0,[&]{return allowTerminal.load();}), b(second,lookup,0,{},[&]{++hibernateRequests;return ERROR_SUCCESS;}, [&]{++updateRequests;return ERROR_SUCCESS;}); require(a.port() && b.port() && a.port()!=b.port(),"test listeners unavailable"); std::jthread polling([&](std::stop_token stop) { while(!stop.stop_requested()){a.poll();b.poll();Sleep(5);} }); const FilesPeer one{first,"127.0.0.1",L"One",a.port()},two{second,"127.0.0.1",L"Two",b.port()}; for(const auto &direction:{std::pair{nullptr,&one}, {&one,nullptr},{&one,&two}}) verifyDirection(direction.first,direction.second,client,key,root); try { FilesConnection unpaired(one,randomHex(16),key); require(false,"unpaired client authenticated"); } catch(const std::system_error &){} FilesConnection host(one,client,key); { const Json hibernate={{"action","hibernate"}}; FilesConnection target(two,client,key); FilesConnection local; require(local.call(hibernate).at("error")==ERROR_ACCESS_DENIED, "local file operations cannot dispatch the LAN power action"); require(host.call(hibernate).at("error")==ERROR_ACCESS_DENIED && hibernateRequests==0, "hibernate requires a separately enabled handler on the target"); require(target.call({{"action","hibernate"},{"command","anything"}}).at("error") ==ERROR_INVALID_PARAMETER && hibernateRequests==0,"hibernate accepts no extra parameters"); require(target.call(hibernate).at("error")==ERROR_SUCCESS && hibernateRequests==1, "hibernate dispatches only to the addressed paired PC"); const Json update={{"action","update"}}; require(host.call(update).at("error")==ERROR_ACCESS_DENIED && updateRequests==0, "update requires a separate handler on the target"); require(target.call({{"action","update"},{"url","https://example.invalid"}}).at("error") ==ERROR_INVALID_PARAMETER && updateRequests==0,"update cannot supply an external package"); require(target.call(update).at("error")==ERROR_SUCCESS && updateRequests==1 && hibernateRequests==1, "update dispatches to the addressed paired PC without invoking hibernate"); } auto deniedCommand=fileRequest("terminalRun",root); deniedCommand["command"]="Write-Output denied"; require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed without consent"); allowTerminal=true; std::string console; const auto exit=runRemoteCommand(host,root, L"[Console]::Out.WriteLine((Get-Location).ProviderPath); " L"[Console]::Error.WriteLine('Тест stderr'); Write-Error 'PowerShell error'; exit 7", [&](std::string_view part){console+=part;}); require(exit==7 && console.find(utf8(root.native()))!=console.npos && console.find(utf8(L"Тест stderr"))!=console.npos,"remote command output or exit code differs"); require(console.find("PowerShell error")!=console.npos && console.find("CLIXML")==console.npos, "remote PowerShell errors were not returned as text"); console.clear(); const auto directoryExit=runRemoteCommand(host,root, L"Write-Progress -Activity 'Hidden progress probe' -Status 'Working'; dir", [&](std::string_view part){console+=part;}); require(directoryExit==0 && console.find("CLIXML")==console.npos && console.find("Hidden progress probe")==console.npos,"remote directory command included progress metadata"); std::stop_source cancel; try { runRemoteCommand(host,root,L"[Console]::Out.WriteLine('Ready'); Start-Sleep -Seconds 30", [&](std::string_view){cancel.request_stop();},cancel.get_token()); require(false,"remote command cancellation did not stop execution"); } catch(const std::system_error &error) { require(error.code().value()==ERROR_CANCELLED,"remote terminal returned the wrong cancellation error"); } allowTerminal=false; require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed after revocation"); std::cout<<"Verified remote PowerShell consent, working directory, streamed output, exit code and cancellation.\n"; const auto edited=root/L"edited.txt", serverFile=root/L"server.txt", snapshot=root/L"snapshot.txt"; save(serverFile,"original remote content"); const auto initial=host.call(fileRequest("stat",serverFile)); checkFileReply(initial); const FileRevision base{initial.at("size"),initial.at("modified")}; FilesConnection local; streamFile(host,local,one.id,serverFile,snapshot,base.size,base.modified,false,false,{}); require(load(snapshot)=="original remote content","remote editor snapshot is incorrect"); save(edited,"editor writeback"); const auto changed=local.call(fileRequest("stat",edited)); checkFileReply(changed); streamFile(local,host,"editor",edited,serverFile,changed.at("size"),changed.at("modified"),true,false,{},&base); require(load(serverFile)=="editor writeback","remote edit did not replace the original"); save(serverFile,"an external replacement of the remote file"); try { streamFile(local,host,"editor",edited,serverFile,changed.at("size"),changed.at("modified"),true,false,{},&base); require(false,"stale editor upload succeeded"); } catch(const std::system_error &error) { require(error.code().value()==ERROR_FILE_INVALID,"stale editor returned the wrong error"); } require(load(serverFile)=="an external replacement of the remote file","stale upload overwrote external edits"); const auto drives=host.call({{"action","drives"}}); checkFileReply(drives); require(drives.at("drives").size()==static_cast(std::popcount(GetLogicalDrives())),"drive mask differs"); const auto denied=host.call(fileRequest("stat",root/L"NUL")); require(denied.at("error")==ERROR_INVALID_NAME,"reserved device accepted"); // A deny ACE on file data applies to the resident's Windows token. const auto protectedFile=root/L"protected.bin"; save(protectedFile,"restricted"); const auto protectedInfo=host.call(fileRequest("stat",protectedFile)); checkFileReply(protectedInfo); PSECURITY_DESCRIPTOR descriptor{}; require(ConvertStringSecurityDescriptorToSecurityDescriptorW( L"D:(D;;0x1;;;WD)(A;;GA;;;WD)",SDDL_REVISION_1,&descriptor,nullptr)!=FALSE, "create test DACL"); const auto applied=SetFileSecurityW(protectedFile.c_str(),DACL_SECURITY_INFORMATION,descriptor); LocalFree(descriptor); require(applied!=FALSE,"apply test DACL"); auto protectedRead=fileRequest("openRead",protectedFile); protectedRead["size"]=protectedInfo.at("size"); protectedRead["modified"]=protectedInfo.at("modified"); require(host.call(protectedRead).at("error")==ERROR_ACCESS_DENIED,"Windows DACL did not deny remote read"); checkFileReply(host.call(fileRequest("remove",protectedFile))); const auto tree=root/L"tree",file=tree/L"original.bin",copy=tree/L"copy.bin",renamed=tree/L"renamed.bin"; checkFileReply(host.call(fileRequest("mkdir",tree))); save(file,"same host"); auto operation=fileRequest("copy",file); operation["target"]=utf8(copy.native()); operation["replace"]=false; operation["append"]=false; save(file,std::string(FileChunk*2,'s')); const auto largeInfo=host.call(fileRequest("stat",file)); operation["size"]=largeInfo.at("size"); operation["modified"]=largeInfo.at("modified"); { FilesConnection interrupted(one,client,key); try { interrupted.call(operation,[](uint64_t done,uint64_t) { if(done==FileChunk) throw std::system_error(WSAECONNRESET,std::system_category()); return true; }); require(false,"same-host interruption expected"); } catch(const std::system_error &e){require(e.code().value()==WSAECONNRESET,"same-host interruption error");} } require(!fs::exists(copy),"same-host interruption published a partial file"); uint64_t firstOffset=UINT64_MAX; for(int i=0;i<100;++i) { const auto reply=host.call(operation,[&](uint64_t done,uint64_t) { firstOffset=std::min(firstOffset,done); return true; }); if(reply.at("error")==ERROR_SHARING_VIOLATION){Sleep(10);continue;} checkFileReply(reply); break; } require(firstOffset==FileChunk && load(copy)==load(file),"same-host copy did not resume"); operation=fileRequest("move",copy); operation["target"]=utf8(renamed.native()); operation["replace"]=false; checkFileReply(host.call(operation)); require(!fs::exists(copy) && load(renamed)==load(file),"same-host rename failed"); checkFileReply(host.call(fileRequest("remove",renamed))); checkFileReply(host.call(fileRequest("remove",file))); checkFileReply(host.call(fileRequest("rmdir",tree))); require(!fs::exists(tree),"same-host directory remains"); } catch(const std::exception &e){std::cerr<