#include #include #include #include #include #include #include #include #include #include #include #include #include "lan_files.h" #include "lan_channel.h" namespace ks::lan { namespace fs = std::filesystem; Json fileRequest(std::string_view action, const fs::path &path) { return {{"action",action},{"path",utf8(path.native())}}; } fs::path filePath(const Json &value) { return wide(value.get()); } void checkFileReply(const Json &reply) { const auto error=reply.at("error").get(); if(error) throw std::system_error(static_cast(error),std::system_category()); } static bool filesPermissionEnabled(const wchar_t *name) { DWORD allowed{},size=sizeof(allowed); return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",name, RRF_RT_REG_DWORD,nullptr,&allowed,&size)==ERROR_SUCCESS && allowed==1; } bool remoteTerminalAllowed() {return filesPermissionEnabled(remoteTerminalPreference);} bool remoteHibernateAllowed() {return filesPermissionEnabled(remoteHibernatePreference);} bool remoteUpdateAllowed() {return filesPermissionEnabled(remoteUpdatePreference);} bool recycleFile(HWND owner,const fs::path &path) { const auto initialized=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED); if(FAILED(initialized)) return false; IFileOperation *operation{}; IShellItem *item{}; auto result=CoCreateInstance(__uuidof(FileOperation),nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&operation)); if(SUCCEEDED(result)) result=operation->SetOperationFlags(FOFX_RECYCLEONDELETE|FOF_SILENT|FOF_NOCONFIRMATION| FOF_NOERRORUI|FOFX_EARLYFAILURE); if(SUCCEEDED(result) && owner) result=operation->SetOwnerWindow(owner); if(SUCCEEDED(result)) result=SHCreateItemFromParsingName(path.c_str(),nullptr,IID_PPV_ARGS(&item)); if(SUCCEEDED(result)) result=operation->DeleteItem(item,nullptr); if(SUCCEEDED(result)) result=operation->PerformOperations(); BOOL aborted=TRUE; if(SUCCEEDED(result)) result=operation->GetAnyOperationsAborted(&aborted); if(item) item->Release(); if(operation) operation->Release(); CoUninitialize(); return SUCCEEDED(result) && !aborted; } namespace { DWORD createJunction(const fs::path &name,const fs::path &target) { if(!target.is_absolute() || target.root_name().native().size()!=2) return ERROR_INVALID_NAME; const auto print=target.lexically_normal().native(); const auto substitute=L"\\??\\"+print; struct MountPointHeader { DWORD tag; WORD dataLength,reserved,substituteOffset,substituteLength,printOffset,printLength; }; const auto substituteBytes=substitute.size()*sizeof(wchar_t); const auto printBytes=print.size()*sizeof(wchar_t); const auto pathBytes=substituteBytes+printBytes+2*sizeof(wchar_t); if(sizeof(MountPointHeader)+pathBytes>MAXIMUM_REPARSE_DATA_BUFFER_SIZE) return ERROR_FILENAME_EXCED_RANGE; const MountPointHeader header{IO_REPARSE_TAG_MOUNT_POINT,static_cast(8+pathBytes),0,0, static_cast(substituteBytes),static_cast(substituteBytes+sizeof(wchar_t)), static_cast(printBytes)}; std::vector buffer(sizeof(header)+pathBytes); std::memcpy(buffer.data(),&header,sizeof(header)); std::memcpy(buffer.data()+sizeof(header),substitute.c_str(),substituteBytes); std::memcpy(buffer.data()+sizeof(header)+header.printOffset,print.c_str(),printBytes); if(!CreateDirectoryW(name.c_str(),nullptr)) return GetLastError(); const auto handle=CreateFileW(name.c_str(),GENERIC_WRITE,0,nullptr,OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr); DWORD error=ERROR_SUCCESS; if(handle==INVALID_HANDLE_VALUE) error=GetLastError(); else { DWORD returned{}; if(!DeviceIoControl(handle,FSCTL_SET_REPARSE_POINT,buffer.data(),static_cast(buffer.size()), nullptr,0,&returned,nullptr)) error=GetLastError(); CloseHandle(handle); } if(error) RemoveDirectoryW(name.c_str()); return error; } constexpr size_t FrameLimit=256*1024; constexpr DWORD SocketTimeout=5000; struct WinSocket { SOCKET value=INVALID_SOCKET; ~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);} }; void socketError() { throw std::system_error(WSAGetLastError(),std::system_category()); } struct Network { Network() { WSADATA data{}; if(const auto error=WSAStartup(MAKEWORD(2,2),&data)) throw std::system_error(error,std::system_category()); } ~Network(){WSACleanup();} }; class Wire { SOCKET socket; std::unique_ptr tx,rx; void bytes(void *buffer,size_t size,bool sending) { auto *next=static_cast(buffer); const auto deadline=GetTickCount64()+SocketTimeout; while(size) { if(GetTickCount64()>=deadline) throw std::system_error(WSAETIMEDOUT,std::system_category()); const auto n=sending?send(socket,next,static_cast(size),0): recv(socket,next,static_cast(size),0); if(n==SOCKET_ERROR) socketError(); if(!n) throw std::system_error(WSAECONNRESET,std::system_category()); size-=n; next+=n; } } public: explicit Wire(SOCKET socket):socket(socket) { if(setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast(&SocketTimeout),sizeof(SocketTimeout)) || setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,reinterpret_cast(&SocketTimeout),sizeof(SocketTimeout))) socketError(); const BOOL yes=TRUE; setsockopt(socket,IPPROTO_TCP,TCP_NODELAY,reinterpret_cast(&yes),sizeof(yes)); } void write(const Json &message) { auto data=Json::to_cbor(message); if(tx) data=tx->encryptPayload(data,FrameLimit-16); if(data.size()>FrameLimit) throw std::runtime_error("LAN file frame too large."); uint32_t length=htonl(static_cast(data.size())); bytes(&length,sizeof(length),true); bytes(data.data(),data.size(),true); } Json read(bool idle=false) { if(idle) { fd_set ready{}; FD_SET(socket,&ready); if(select(0,&ready,nullptr,nullptr,nullptr)==SOCKET_ERROR) socketError(); } uint32_t length{}; bytes(&length,sizeof(length),false); length=ntohl(length); if(!length || length>(rx?FrameLimit:1024)) throw std::runtime_error("Invalid LAN file frame."); Bytes data(length); bytes(data.data(),data.size(),false); if(rx) data=rx->decryptPayload(data,FrameLimit-16); return Json::from_cbor(data); } void authenticate(const std::string &secret,const std::string &client,const std::string &server, const std::string &challenge,const std::string &nonce,bool outbound) { if(!identifier(client)||!identifier(server)||client==server||!identifier(challenge)||!identifier(nonce)) throw std::runtime_error("Invalid LAN file session."); const auto context="KSwitcher files v1|"+client+"|"+server+"|"+challenge+"|"+nonce; tx=std::make_unique(mac(secret,context+(outbound?"|request":"|response"))); rx=std::make_unique(mac(secret,context+(outbound?"|response":"|request"))); } }; void connectPeer(SOCKET socket,const FilesPeer &peer) { sockaddr_in address{}; address.sin_family=AF_INET; address.sin_port=htons(peer.port); if(InetPtonA(AF_INET,peer.address.c_str(),&address.sin_addr)!=1) throw std::system_error(WSAEHOSTUNREACH,std::system_category()); u_long mode=1; if(ioctlsocket(socket,FIONBIO,&mode)) socketError(); if(connect(socket,reinterpret_cast(&address),sizeof(address))) { if(WSAGetLastError()!=WSAEWOULDBLOCK) socketError(); fd_set writable{},failed{}; FD_SET(socket,&writable); FD_SET(socket,&failed); timeval timeout{2,0}; const auto result=select(0,nullptr,&writable,&failed,&timeout); if(result==SOCKET_ERROR) socketError(); if(!result) throw std::system_error(WSAETIMEDOUT,std::system_category()); int error{},size=sizeof(error); if(getsockopt(socket,SOL_SOCKET,SO_ERROR,reinterpret_cast(&error),&size)) socketError(); if(error) throw std::system_error(error,std::system_category()); } mode=0; if(ioctlsocket(socket,FIONBIO,&mode)) socketError(); } uint64_t fileSize(DWORD high,DWORD low){return (uint64_t(high)<<32)|low;} Json ok(){return {{"error",ERROR_SUCCESS}};} Json failure(DWORD error=GetLastError()){return {{"error",error?error:ERROR_GEN_FAILURE}};} struct FileHandle { HANDLE value=INVALID_HANDLE_VALUE; void close(){if(value!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(value,INVALID_HANDLE_VALUE));} ~FileHandle(){close();} }; DWORD requestSystemHibernate() { wchar_t system[MAX_PATH]{}; const auto length=GetSystemDirectoryW(system,MAX_PATH); if(!length) return GetLastError(); if(length>=MAX_PATH) return ERROR_INSUFFICIENT_BUFFER; const auto executable=fs::path(system)/L"shutdown.exe"; wchar_t command[]=L"shutdown.exe /h"; STARTUPINFOW startup{sizeof(startup)}; PROCESS_INFORMATION child{}; if(!CreateProcessW(executable.c_str(),command,nullptr,nullptr,FALSE,CREATE_NO_WINDOW, nullptr,system,&startup,&child)) return GetLastError(); CloseHandle(child.hThread); FileHandle process{child.hProcess}; const auto wait=WaitForSingleObject(process.value,3000); if(wait==WAIT_TIMEOUT) return ERROR_TIMEOUT; if(wait!=WAIT_OBJECT_0) return GetLastError(); DWORD exitCode{}; return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError(); } struct RemoteCommand { FileHandle job,process,output; void stop() { job.close(); process.close(); output.close(); } DWORD start(const fs::path &directory,const std::wstring &command) { if(process.value!=INVALID_HANDLE_VALUE) return ERROR_BUSY; if(command.empty() || command.size()>12000 || command.find(L'\0')!=command.npos) return ERROR_INVALID_PARAMETER; const auto script=L"$ProgressPreference='SilentlyContinue'; " L"[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); " L"$OutputEncoding=[Console]::OutputEncoding;\r\n"+command; const auto data=reinterpret_cast(script.data()); const auto bytes=static_cast(script.size()*sizeof(wchar_t)); constexpr DWORD encoding=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF; DWORD length{}; if(!CryptBinaryToStringW(data,bytes,encoding,nullptr,&length)) return GetLastError(); std::wstring encoded(length,L'\0'); if(!CryptBinaryToStringW(data,bytes,encoding,encoded.data(),&length)) return GetLastError(); encoded.resize(length); // Windows PowerShell serializes its error stream as CLIXML with -EncodedCommand. // Decode the command inside a fixed text-mode expression instead. auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command " L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+ encoded+L"'))))\""; wchar_t system[MAX_PATH]{}; if(!GetSystemDirectoryW(system,MAX_PATH)) return GetLastError(); const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe"; FileHandle token,restricted,read,write,input,processJob; if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY| TOKEN_ADJUST_DEFAULT,&token.value) || !CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr, &restricted.value)) return GetLastError(); PSID medium{}; if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError(); TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}}; const auto limited=SetTokenInformation(restricted.value,TokenIntegrityLevel,&label, sizeof(label)+GetLengthSid(medium)); const auto tokenError=GetLastError(); LocalFree(medium); if(!limited) return tokenError; SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE}; if(!CreatePipe(&read.value,&write.value,&inheritable,0) || !SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0)) return GetLastError(); input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable, OPEN_EXISTING,0,nullptr); if(input.value==INVALID_HANDLE_VALUE) return GetLastError(); const auto createdJob=CreateJobObjectW(nullptr,nullptr); if(!createdJob) return GetLastError(); processJob.value=createdJob; JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if(!SetInformationJobObject(processJob.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return GetLastError(); SIZE_T attributeBytes{}; InitializeProcThreadAttributeList(nullptr,1,0,&attributeBytes); std::vector storage(attributeBytes); const auto attributes=reinterpret_cast(storage.data()); if(!InitializeProcThreadAttributeList(attributes,1,0,&attributeBytes)) return GetLastError(); HANDLE inherited[]{input.value,write.value}; STARTUPINFOEXW startup{}; startup.StartupInfo.cb=sizeof(startup); startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES; startup.StartupInfo.hStdInput=input.value; startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=write.value; startup.lpAttributeList=attributes; PROCESS_INFORMATION child{}; const auto started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited,sizeof(inherited),nullptr,nullptr) && CreateProcessAsUserW(restricted.value,shell.c_str(),arguments.data(),nullptr,nullptr,TRUE, CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr, directory.c_str(),&startup.StartupInfo,&child); const auto processError=GetLastError(); DeleteProcThreadAttributeList(attributes); if(!started) return processError; FileHandle thread{child.hThread},childProcess{child.hProcess}; if(!AssignProcessToJobObject(processJob.value,childProcess.value) || ResumeThread(thread.value)==DWORD(-1)) { const auto error=GetLastError(); TerminateProcess(childProcess.value,error); return error; } job.value=std::exchange(processJob.value,INVALID_HANDLE_VALUE); process.value=std::exchange(childProcess.value,INVALID_HANDLE_VALUE); output.value=std::exchange(read.value,INVALID_HANDLE_VALUE); return ERROR_SUCCESS; } Json poll() { if(process.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE); const auto wait=WaitForSingleObject(process.value,0); if(wait==WAIT_FAILED) return failure(); DWORD available{}; if(!PeekNamedPipe(output.value,nullptr,0,nullptr,&available,nullptr) && GetLastError()!=ERROR_BROKEN_PIPE) return failure(); Bytes bytes(std::min(available,FileChunk)); DWORD read{}; if(!bytes.empty() && !ReadFile(output.value,bytes.data(),static_cast(bytes.size()),&read,nullptr)) return failure(); bytes.resize(read); const bool done=wait==WAIT_OBJECT_0 && bytes.empty(); DWORD exitCode{}; if(done) { if(!GetExitCodeProcess(process.value,&exitCode)) return failure(); stop(); } return {{"error",0},{"data",Json::binary(std::move(bytes))},{"done",done},{"exitCode",exitCode}}; } }; fs::path temporaryFile(const fs::path &target) { return target.parent_path()/wide(".kswitcher-"+randomHex(16)+".tmp"); } std::string hashPrefix(HANDLE file,uint64_t size,const FileProgress &progress,uint64_t offset=0) { struct Hash { BCRYPT_ALG_HANDLE algorithm{}; BCRYPT_HASH_HANDLE value{}; ~Hash(){if(value) BCryptDestroyHash(value);if(algorithm) BCryptCloseAlgorithmProvider(algorithm,0);} } hash; const auto checked=[](NTSTATUS status) { if(status<0) throw std::system_error(ERROR_GEN_FAILURE,std::system_category()); }; LARGE_INTEGER position{}; position.QuadPart=offset; if(!SetFilePointerEx(file,position,nullptr,FILE_BEGIN)) throw std::system_error(GetLastError(),std::system_category()); checked(BCryptOpenAlgorithmProvider(&hash.algorithm,BCRYPT_SHA256_ALGORITHM,nullptr,0)); checked(BCryptCreateHash(hash.algorithm,&hash.value,nullptr,0,nullptr,0,0)); Bytes buffer(FileChunk),digest(32); const auto total=size; auto last=GetTickCount64(); while(size) { const auto now=GetTickCount64(); if(progress && now-last>=100) { if(!progress(total-size,total)) throw std::system_error(ERROR_CANCELLED,std::system_category()); last=now; } const auto count=static_cast(std::min(size,buffer.size())); DWORD read{}; if(!ReadFile(file,buffer.data(),count,&read,nullptr) || read!=count) throw std::system_error(ERROR_READ_FAULT,std::system_category()); checked(BCryptHashData(hash.value,buffer.data(),read,0)); size-=read; } checked(BCryptFinishHash(hash.value,digest.data(),static_cast(digest.size()),0)); std::string hex; for(const auto byte:digest){hex+="0123456789abcdef"[byte>>4];hex+="0123456789abcdef"[byte&15];} return hex; } class FileOperations { FilesListener::TerminalPermission terminalPermission; FilesListener::HostAction hibernate,update; RemoteCommand terminal; bool remote; HANDLE search=INVALID_HANDLE_VALUE; WIN32_FIND_DATAW entry{}; bool pending{}; FileHandle input,output; fs::path temporary,target; bool resumable{}; uint64_t appendBase{},expectedSize{}; void closeSearch() { if(search!=INVALID_HANDLE_VALUE) FindClose(std::exchange(search,INVALID_HANDLE_VALUE)); } void discard(bool removePartial=false) { output.close(); if(resumable && !removePartial) {temporary.clear();resumable=false;return;} resumable=false; if(!temporary.empty() && !DeleteFileW(temporary.c_str()) && GetLastError()==ERROR_ACCESS_DENIED) { SetFileAttributesW(temporary.c_str(),FILE_ATTRIBUTE_NORMAL); DeleteFileW(temporary.c_str()); } temporary.clear(); } fs::path path(const Json &value) const { auto result=filePath(value); const auto &name=result.native(); if(name.find(L'\0')!=name.npos) throw std::system_error(ERROR_INVALID_NAME,std::system_category()); if(remote) { // Only drive paths from the remote Windows namespace. Reject NT devices and streams. if(name.size()<3 || !((name[0]>=L'A'&&name[0]<=L'Z')||(name[0]>=L'a'&&name[0]<=L'z')) || name[1]!=L':' || (name[2]!=L'\\' && name[2]!=L'/') || name.find(L':',2)!=name.npos) throw std::system_error(ERROR_INVALID_NAME,std::system_category()); result=result.lexically_normal(); for(const auto &part:result.relative_path()) { const auto &component=part.native(); if(component.empty()) continue; const auto dosName=component.substr(0,component.find_first_of(L". ")); if(part==L".." || component.find_first_of(L"<>|?*\"")!=component.npos || component.back()==L' ' || component.back()==L'.' || std::any_of(component.begin(),component.end(),[](wchar_t ch){return ch<32;}) || _wcsicmp(dosName.c_str(),L"CON")==0 || _wcsicmp(dosName.c_str(),L"PRN")==0 || _wcsicmp(dosName.c_str(),L"AUX")==0 || _wcsicmp(dosName.c_str(),L"NUL")==0 || (dosName.size()==4 && (_wcsnicmp(dosName.c_str(),L"COM",3)==0 || _wcsnicmp(dosName.c_str(),L"LPT",3)==0) && std::wstring_view(L"123456789¹²³").find(dosName.back())!=component.npos)) throw std::system_error(ERROR_INVALID_NAME,std::system_category()); } } return result; } Json listNext() { auto reply=ok(); auto &entries=reply["entries"]=Json::array(); while(search!=INVALID_HANDLE_VALUE && entries.size()<64) { if(!pending && !FindNextFileW(search,&entry)) { const auto error=GetLastError(); closeSearch(); if(error!=ERROR_NO_MORE_FILES) return failure(error); break; } pending=false; const std::wstring name(entry.cFileName); if(name==L"." || name==L".." || ((entry.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN) && name.starts_with(L".kswitcher-") && name.ends_with(L".partial") && name.size()==83)) continue; entries.push_back({{"name",utf8(name)},{"attributes",entry.dwFileAttributes}, {"size",fileSize(entry.nFileSizeHigh,entry.nFileSizeLow)}, {"modified",fileSize(entry.ftLastWriteTime.dwHighDateTime,entry.ftLastWriteTime.dwLowDateTime)}}); } reply["more"]=search!=INVALID_HANDLE_VALUE; return reply; } static DWORD CALLBACK copyProgress(LARGE_INTEGER total,LARGE_INTEGER transferred,LARGE_INTEGER,LARGE_INTEGER, DWORD,DWORD,HANDLE,HANDLE,LPVOID context) { const auto &callback=*static_cast(context); try {return !callback || callback(transferred.QuadPart,total.QuadPart)?PROGRESS_CONTINUE:PROGRESS_CANCEL;} catch(...) {return PROGRESS_CANCEL;} } Json copy(const fs::path &source,const fs::path &destination,bool replace,bool append, const FileProgress &progress) { discard(); temporary=temporaryFile(destination); if(!append) { if(!CopyFileExW(source.c_str(),temporary.c_str(),copyProgress, const_cast(&progress),nullptr,COPY_FILE_FAIL_IF_EXISTS)) { const auto error=GetLastError(); if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS) temporary.clear(); return failure(error); } } else { FileHandle in{CreateFileW(source.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,0,nullptr)}; if(in.value==INVALID_HANDLE_VALUE){temporary.clear();return failure();} if(!CopyFileExW(destination.c_str(),temporary.c_str(),nullptr,nullptr,nullptr,COPY_FILE_FAIL_IF_EXISTS)) { const auto error=GetLastError(); if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS) temporary.clear(); return failure(error); } if(!SetFileAttributesW(temporary.c_str(),FILE_ATTRIBUTE_NORMAL)) return failure(); FileHandle out{CreateFileW(temporary.c_str(),FILE_APPEND_DATA,0,nullptr,OPEN_EXISTING,0,nullptr)}; if(out.value==INVALID_HANDLE_VALUE) return failure(); LARGE_INTEGER size{}; if(!GetFileSizeEx(in.value,&size)) return failure(); Bytes buffer(FileChunk); uint64_t done=0; for(;;) { DWORD read{},written{}; if(!ReadFile(in.value,buffer.data(),static_cast(buffer.size()),&read,nullptr)) return failure(); if(!read) break; if(!WriteFile(out.value,buffer.data(),read,&written,nullptr)) return failure(); if(written!=read) return failure(ERROR_WRITE_FAULT); done+=written; if(progress && !progress(done,size.QuadPart)) return failure(ERROR_CANCELLED); } } return commit(destination,replace); } static Json replaceFile(const fs::path &source,const fs::path &destination,bool replace) { const auto attributes=GetFileAttributesW(destination.c_str()); const bool readOnly=replace && attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_READONLY)!=0; if(replace && attributes!=INVALID_FILE_ATTRIBUTES && (attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))) return failure(ERROR_ACCESS_DENIED); if(readOnly && !SetFileAttributesW(destination.c_str(),attributes&~FILE_ATTRIBUTE_READONLY)) return failure(); if(!MoveFileExW(source.c_str(),destination.c_str(),replace?MOVEFILE_REPLACE_EXISTING:0)) { const auto error=GetLastError(); if(readOnly) SetFileAttributesW(destination.c_str(),attributes); return failure(error); } return ok(); } Json commit(const fs::path &destination,bool replace) { const auto reply=replaceFile(temporary,destination,replace); if(reply.at("error")==ERROR_SUCCESS) temporary.clear(); return reply; } public: explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={}, FilesListener::HostAction hibernateAction={},FilesListener::HostAction updateAction={}): terminalPermission(std::move(permission)),hibernate(std::move(hibernateAction)), update(std::move(updateAction)),remote(remote){} ~FileOperations(){closeSearch();discard();} Json call(const Json &request,const FileProgress &progress) { try {return perform(request,progress);} catch(const std::system_error &e) { if(e.code().value()==ERROR_CANCELLED) discard(true); return failure(static_cast(e.code().value())); } } Json perform(const Json &request,const FileProgress &progress) { const auto action=request.at("action").get(); if(action=="hibernate" || action=="update") { if(request.size()!=1) return failure(ERROR_INVALID_PARAMETER); const auto &hostAction=action=="hibernate"?hibernate:update; if(!remote || !hostAction) return failure(ERROR_ACCESS_DENIED); const auto error=hostAction(); return error?failure(error):ok(); } if(action=="terminalRun" || action=="terminalPoll" || action=="terminalCancel") { if(!remote || !terminalPermission || !terminalPermission()) { terminal.stop(); return failure(ERROR_ACCESS_DENIED); } if(action=="terminalCancel") {terminal.stop();return ok();} if(action=="terminalPoll") return terminal.poll(); const auto error=terminal.start(path(request.at("path")),wide(request.at("command").get())); return error?failure(error):ok(); } if(action=="drives") { auto reply=ok(); auto &drives=reply["drives"]=Json::array(); const auto mask=GetLogicalDrives(); if(!mask) return failure(); for(int letter=0;letter<26;++letter) { if(!(mask&(1UL<(L'A'+letter),L':',L'\\',0}; const auto type=GetDriveTypeW(root); ULARGE_INTEGER total{},free{}; if(type==DRIVE_FIXED || type==DRIVE_RAMDISK) GetDiskFreeSpaceExW(root,&free,&total,nullptr); drives.push_back({{"path",utf8(root)},{"type",type},{"total",total.QuadPart},{"free",free.QuadPart}}); } return reply; } if(action=="listNext") return listNext(); if(action=="read") { Bytes data(FileChunk); DWORD count{}; if(!ReadFile(input.value,data.data(),static_cast(data.size()),&count,nullptr)) return failure(); data.resize(count); return {{"error",0},{"data",Json::binary(std::move(data))}}; } if(action=="closeRead"){input.close();return ok();} if(action=="abort"){discard(true);return ok();} if(action=="hashRead") { if(input.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE); return {{"error",0},{"hash",hashPrefix(input.value,request.at("size"),progress)}}; } if(action=="write") { const auto &data=request.at("data").get_binary(); if(data.size()>FileChunk) return failure(ERROR_INVALID_DATA); LARGE_INTEGER zero{},start{}; if(!SetFilePointerEx(output.value,zero,&start,FILE_CURRENT)) return failure(); const auto end=uint64_t(start.QuadPart)+data.size(); if(endexpectedSize) return failure(ERROR_INVALID_DATA); DWORD count{}; if(WriteFile(output.value,data.data(),static_cast(data.size()),&count,nullptr) && count==data.size() && FlushFileBuffers(output.value)) return ok(); const auto error=GetLastError(); if(!SetFilePointerEx(output.value,start,nullptr,FILE_BEGIN) || !SetEndOfFile(output.value)) discard(true); return failure(error?error:ERROR_WRITE_FAULT); } if(action=="commit" || action=="commitEdit") { if(output.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE); LARGE_INTEGER size{}; if(!GetFileSizeEx(output.value,&size)) return failure(); if(uint64_t(size.QuadPart)!=appendBase+expectedSize) return failure(ERROR_FILE_INVALID); const auto stamp=request.at("modified").get(); const FILETIME time{static_cast(stamp),static_cast(stamp>>32)}; if(!SetFileTime(output.value,nullptr,nullptr,&time) || !FlushFileBuffers(output.value)) return failure(); output.close(); static std::mutex publicationMutex; const std::lock_guard publication(publicationMutex); if(action=="commitEdit") { WIN32_FILE_ATTRIBUTE_DATA existing{}; if(!GetFileAttributesExW(target.c_str(),GetFileExInfoStandard,&existing) || (existing.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_READONLY)) || fileSize(existing.nFileSizeHigh,existing.nFileSizeLow)!=request.at("expectedSize").get() || fileSize(existing.ftLastWriteTime.dwHighDateTime,existing.ftLastWriteTime.dwLowDateTime)!= request.at("expectedModified").get()) { discard(true); return failure(ERROR_FILE_INVALID); } const auto attributes=FILE_ATTRIBUTE_ARCHIVE| (existing.dwFileAttributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM| FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)); if(!SetFileAttributesW(temporary.c_str(),attributes)) return failure(); return commit(target,true); } const auto reply=commit(target,request.at("replace").get()); if(reply.at("error")==ERROR_SUCCESS) SetFileAttributesW(target.c_str(),FILE_ATTRIBUTE_ARCHIVE); return reply; } const auto name=path(request.at("path")); if(action=="list") { closeSearch(); search=FindFirstFileW((name/L"*").c_str(),&entry); pending=search!=INVALID_HANDLE_VALUE; if(!pending && GetLastError()!=ERROR_FILE_NOT_FOUND) return failure(); return listNext(); } if(action=="stat") { WIN32_FILE_ATTRIBUTE_DATA data{}; if(!GetFileAttributesExW(name.c_str(),GetFileExInfoStandard,&data)) return failure(); return {{"error",0},{"attributes",data.dwFileAttributes},{"editCommit",true}, {"size",fileSize(data.nFileSizeHigh,data.nFileSizeLow)}, {"modified",fileSize(data.ftLastWriteTime.dwHighDateTime,data.ftLastWriteTime.dwLowDateTime)}}; } if(action=="canonical") { std::error_code error; const auto canonical=fs::weakly_canonical(name,error); return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}}; } if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure(); if(action=="mkdir-link") { const auto target=path(request.at("target")); if(target.empty()) return failure(ERROR_INVALID_NAME); const auto kind=request.at("kind").get(); if(kind=="junction") { const auto error=createJunction(name,target); return error?failure(error):ok(); } if(kind!="symlink") return failure(ERROR_INVALID_PARAMETER); return CreateSymbolicLinkW(name.c_str(),target.c_str(), SYMBOLIC_LINK_FLAG_DIRECTORY|SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)?ok():failure(); } if(action=="rmdir") return RemoveDirectoryW(name.c_str())?ok():failure(); if(action=="recycle") return recycleFile(nullptr,name)?ok():failure(ERROR_ACCESS_DENIED); if(action=="remove") { if(request.contains("size")) { WIN32_FILE_ATTRIBUTE_DATA data{}; if(!GetFileAttributesExW(name.c_str(),GetFileExInfoStandard,&data)) return failure(); if((data.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) || fileSize(data.nFileSizeHigh,data.nFileSizeLow)!=request.at("size") || fileSize(data.ftLastWriteTime.dwHighDateTime,data.ftLastWriteTime.dwLowDateTime)!=request.at("modified")) return failure(ERROR_FILE_INVALID); } const auto attributes=GetFileAttributesW(name.c_str()); if(attributes==INVALID_FILE_ATTRIBUTES) return failure(); if(attributes&FILE_ATTRIBUTE_DIRECTORY) return RemoveDirectoryW(name.c_str())?ok():failure(); const bool clear=request.value("readOnly",false) && (attributes&FILE_ATTRIBUTE_READONLY) && !(attributes&FILE_ATTRIBUTE_REPARSE_POINT); if(clear && !SetFileAttributesW(name.c_str(),attributes&~FILE_ATTRIBUTE_READONLY)) return failure(); if(DeleteFileW(name.c_str())) return ok(); const auto error=GetLastError(); if(clear) SetFileAttributesW(name.c_str(),attributes); return failure(error); } if(action=="move") { const auto destination=path(request.at("target")); const bool replace=request.at("replace").get(); if(!replace) return MoveFileExW(name.c_str(),destination.c_str(),0)?ok():failure(); std::error_code error; if(fs::equivalent(name,destination,error)) return failure(ERROR_ALREADY_EXISTS); return replaceFile(name,destination,true); } if(action=="copy") { const auto destination=path(request.at("target")); if(remote && request.contains("size")) { // Both streams execute inside the serving process. FilesConnection source,target; streamFile(source,target,"same host",name,destination,request.at("size"),request.at("modified"), request.at("replace"),request.at("append"),progress); return ok(); } return copy(name,destination,request.at("replace"),request.at("append"),progress); } if(action=="openRead") { input.close(); input.value=CreateFileW(name.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_SEQUENTIAL_SCAN,nullptr); if(input.value==INVALID_HANDLE_VALUE) return failure(); BY_HANDLE_FILE_INFORMATION info{}; if(!GetFileInformationByHandle(input.value,&info)) return failure(); if(info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) return failure(ERROR_ACCESS_DENIED); const auto size=fileSize(info.nFileSizeHigh,info.nFileSizeLow); const auto modified=fileSize(info.ftLastWriteTime.dwHighDateTime,info.ftLastWriteTime.dwLowDateTime); if(size!=request.at("size") || modified!=request.at("modified")) return failure(ERROR_FILE_INVALID); return ok(); } if(action=="openWrite") { discard(); target=name; const auto transfer=request.at("transfer").get(); if(transfer.size()!=64 || transfer.find_first_not_of("0123456789abcdef")!=transfer.npos) return failure(ERROR_INVALID_DATA); expectedSize=request.at("size").get(); const bool append=request.value("append",false); appendBase=0; auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial"); FileHandle original; if(append) { original.value=CreateFileW(target.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,0,nullptr); if(original.value==INVALID_HANDLE_VALUE) return failure(); BY_HANDLE_FILE_INFORMATION info{}; if(!GetFileInformationByHandle(original.value,&info)) return failure(); appendBase=fileSize(info.nFileSizeHigh,info.nFileSizeLow); } output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN|FILE_FLAG_OPEN_REPARSE_POINT,nullptr); if(output.value==INVALID_HANDLE_VALUE) return failure(); const bool created=GetLastError()!=ERROR_ALREADY_EXISTS; BY_HANDLE_FILE_INFORMATION info{}; if(!GetFileInformationByHandle(output.value,&info)) return failure(); if(info.nNumberOfLinks!=1 || (info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))) return failure(ERROR_ACCESS_DENIED); temporary=staging; resumable=true; if(created && appendBase) { Bytes buffer(FileChunk); for(uint64_t left=appendBase;left;) { const auto count=static_cast(std::min(left,buffer.size())); DWORD read{},written{}; if(!ReadFile(original.value,buffer.data(),count,&read,nullptr) || read!=count || !WriteFile(output.value,buffer.data(),read,&written,nullptr) || written!=read) { discard(true); return failure(ERROR_WRITE_FAULT); } left-=written; } } const auto size=created?appendBase:fileSize(info.nFileSizeHigh,info.nFileSizeLow); const bool valid=size>=appendBase && size-appendBase<=expectedSize && (!appendBase || hashPrefix(original.value,appendBase,progress)==hashPrefix(output.value,appendBase,progress)); if(!valid) { discard(true); return {{"error",0},{"restart",true}}; } const auto offset=size-appendBase; return {{"error",0},{"offset",offset},{"hash",hashPrefix(output.value,offset,progress,appendBase)}}; } return failure(ERROR_INVALID_FUNCTION); } }; } struct FilesConnection::Impl { std::optional network; WinSocket socket; std::unique_ptr wire; FileOperations local{false}; Impl()=default; explicit Impl(const FilesPeer *peer) { if(!peer) return; const auto pairing=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024))); if(!pairing.value("enabled",false) || !pairing.at("trusted").contains(peer->id)) throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); const auto id=pairing.at("id").get(); const auto key=pairing.at("trusted").at(peer->id).at("key").get(); connect(*peer,id,key); } void connect(const FilesPeer &peer,const std::string &id,const std::string &key) { network.emplace(); socket.value=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(socket.value==INVALID_SOCKET) socketError(); connectPeer(socket.value,peer); wire=std::make_unique(socket.value); const auto nonce=randomHex(16); wire->write({{"version",1},{"client",id},{"server",peer.id},{"nonce",nonce}}); const auto challenge=wire->read().at("challenge").get(); wire->authenticate(key,id,peer.id,challenge,nonce,true); wire->write({{"action","authenticate"}}); checkFileReply(wire->read()); } }; DWORD hibernateFromPairedPC() { if(!remoteHibernateAllowed()) return ERROR_ACCESS_DENIED; return requestSystemHibernate(); } FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique(peer)){} FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key): impl(std::make_unique()) { impl->connect(peer,local,key); } FilesConnection::~FilesConnection()=default; Json FilesConnection::call(const Json &request,const FileProgress &progress) { if(!impl->wire) return impl->local.call(request,progress); impl->wire->write(request); for(;;) { auto reply=impl->wire->read(); if(!reply.contains("progress")) return reply; const auto &value=reply.at("progress"); const bool proceed=!progress || progress(value[0].get(),value[1].get()); impl->wire->write({{"continue",proceed}}); } } void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId, const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified, bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination) { auto openSource=fileRequest("openRead",from); openSource["size"]=size; openSource["modified"]=modified; checkFileReply(source.call(openSource)); auto upload=fileRequest("openWrite",to); upload["append"]=append; upload["size"]=size; const auto identity=Json::array({sourceId,ks::utf8(from.native()),ks::utf8(to.native()), size,modified,append}); upload["transfer"]=ks::lan::mac("KSwitcher partial v1",identity.dump()); uint64_t done=0; const auto resumeProgress=[&](uint64_t,uint64_t){return !progress || progress(done,size);}; try { for(int attempt=0;;++attempt) { auto reply=target.call(upload,resumeProgress); checkFileReply(reply); if(!reply.value("restart",false)) { done=reply.at("offset"); const auto sourceHash=source.call({{"action","hashRead"},{"size",done}},resumeProgress); checkFileReply(sourceHash); if(sourceHash.at("hash")==reply.at("hash")) break; checkFileReply(target.call({{"action","abort"}})); } if(attempt>0) throw std::system_error(ERROR_FILE_INVALID,std::system_category()); } while(!progress || progress(done,size)) { auto packet=source.call({{"action","read"}}); checkFileReply(packet); auto &data=packet.at("data").get_binary(); if(data.empty()) { if(done!=size) throw std::system_error(ERROR_FILE_INVALID,std::system_category()); Json commit{{"action",expectedDestination?"commitEdit":"commit"},{"replace",replace},{"modified",modified}}; if(expectedDestination) { commit["expectedSize"]=expectedDestination->size; commit["expectedModified"]=expectedDestination->modified; } checkFileReply(target.call(commit)); checkFileReply(source.call({{"action","closeRead"}})); return; } const auto chunkSize=data.size(); checkFileReply(target.call({{"action","write"},{"data",std::move(packet.at("data"))}})); done+=chunkSize; } throw std::system_error(ERROR_CANCELLED,std::system_category()); } catch(const std::system_error &error) { if(error.code().value()==ERROR_CANCELLED) checkFileReply(target.call({{"action","abort"}})); throw; } } DWORD runRemoteCommand(FilesConnection &host,const fs::path &directory,std::wstring_view command, const std::function &output,std::stop_token stop) { if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category()); auto request=fileRequest("terminalRun",directory); request["command"]=utf8(std::wstring(command)); checkFileReply(host.call(request)); while(!stop.stop_requested()) { const auto reply=host.call({{"action","terminalPoll"}}); checkFileReply(reply); const auto &bytes=reply.at("data").get_binary(); if(!bytes.empty()) output({reinterpret_cast(bytes.data()),bytes.size()}); if(reply.at("done").get()) return reply.at("exitCode").get(); if(bytes.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(60)); } checkFileReply(host.call({{"action","terminalCancel"}})); throw std::system_error(ERROR_CANCELLED,std::system_category()); } struct FilesListener::Impl { struct Client { WinSocket socket; std::atomic done{}; std::thread worker; ~Client() { shutdown(socket.value,SD_BOTH); if(worker.joinable()) worker.join(); } }; std::string local; PairKey key; TerminalPermission terminalPermission; HostAction hibernate,update; WinSocket listener; std::vector> clients; uint16_t boundPort{}; Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission,HostAction hibernateAction, HostAction updateAction): local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)), hibernate(std::move(hibernateAction)),update(std::move(updateAction)) { listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(listener.value==INVALID_SOCKET) return; BOOL exclusive=TRUE; u_long mode=1; sockaddr_in address{}; address.sin_family=AF_INET; address.sin_port=htons(port); if(setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast(&exclusive),sizeof(exclusive)) || ioctlsocket(listener.value,FIONBIO,&mode) || bind(listener.value,reinterpret_cast(&address),sizeof(address)) || listen(listener.value,8)) { closesocket(std::exchange(listener.value,INVALID_SOCKET)); return; } int length=sizeof(address); if(!getsockname(listener.value,reinterpret_cast(&address),&length)) boundPort=ntohs(address.sin_port); } void serve(SOCKET socket) { Wire wire(socket); const auto hello=wire.read(); const auto peer=hello.at("client").get(); const auto nonce=hello.at("nonce").get(); if(hello.at("version")!=1 || hello.at("server")!=local || !identifier(peer) || !identifier(nonce)) return; const auto secret=key(peer); if(secret.empty()) return; const auto challenge=randomHex(16); wire.write({{"challenge",challenge}}); wire.authenticate(secret,peer,local,challenge,nonce,false); if(wire.read().at("action")!="authenticate") return; wire.write(ok()); FileOperations operations(true,terminalPermission,hibernate,update); for(;;) { const auto request=wire.read(true); if(!equal(key(peer),secret)) return; wire.write(operations.call(request,[&](uint64_t done,uint64_t total) { if(!equal(key(peer),secret)) throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); wire.write({{"progress",{done,total}}}); const bool proceed=wire.read(true).value("continue",false); if(!equal(key(peer),secret)) throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); return proceed; })); } } void poll() { std::erase_if(clients,[](const auto &client){return client->done.load();}); if(listener.value==INVALID_SOCKET || clients.size()>=16) return; sockaddr_in address{}; int size=sizeof(address); WinSocket accepted{accept(listener.value,reinterpret_cast(&address),&size)}; const auto ip=ntohl(address.sin_addr.s_addr); if((ip>>24)!=10 && (ip>>24)!=127 && (ip>>20)!=0xac1 && (ip>>16)!=0xc0a8 && (ip>>16)!=0xa9fe) return; if(accepted.value==INVALID_SOCKET) return; u_long mode=0; if(ioctlsocket(accepted.value,FIONBIO,&mode)) return; auto client=std::make_unique(); client->socket.value=std::exchange(accepted.value,INVALID_SOCKET); auto *connection=client.get(); connection->worker=std::thread([this,connection] { try {serve(connection->socket.value);} catch(const std::exception &) {} connection->done=true; }); clients.push_back(std::move(client)); } }; FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission, HostAction hibernate,HostAction update): impl(std::make_unique(std::move(local),std::move(key),port,std::move(terminalPermission), std::move(hibernate),std::move(update))){} FilesListener::~FilesListener()=default; uint16_t FilesListener::port()const{return impl->boundPort;} void FilesListener::poll(){impl->poll();} }