#include "pipe.h" #include "protocol.h" #include #include #include #include #include #pragma comment(lib,"advapi32.lib") namespace browser_bridge { namespace { using Handle=std::unique_ptr; std::wstring UserSid() { HANDLE raw=nullptr; if (!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&raw)) return {}; Handle token(raw,&CloseHandle); DWORD size=0; GetTokenInformation(token.get(),TokenUser,nullptr,0,&size); std::vector buffer(size); if (!size || !GetTokenInformation(token.get(),TokenUser,buffer.data(),size,&size)) return {}; LPWSTR sid=nullptr; if (!ConvertSidToStringSidW(reinterpret_cast(buffer.data())->User.Sid,&sid)) return {}; std::wstring result(sid); LocalFree(sid); return result; } bool Complete(HANDLE pipe,OVERLAPPED& operation,HANDLE stop,ULONGLONG deadline,DWORD& done) { HANDLE waits[]={operation.hEvent,stop}; ULONGLONG now=GetTickCount64(); DWORD timeout=now>=deadline?0:static_cast(deadline-now); DWORD wait=WaitForMultipleObjects(stop?2:1,waits,FALSE,timeout); if (wait!=WAIT_OBJECT_0) { CancelIoEx(pipe,&operation); GetOverlappedResult(pipe,&operation,&done,TRUE); return false; } return GetOverlappedResult(pipe,&operation,&done,FALSE)!=FALSE; } bool Bytes(HANDLE pipe,void* data,DWORD size,bool write,HANDLE stop,ULONGLONG deadline) { Handle event(CreateEventW(nullptr,TRUE,FALSE,nullptr),&CloseHandle); if (!event) return false; auto* bytes=static_cast(data); DWORD total=0; while (total(json.size()):0; if (!Bytes(pipe,&size,4,write,stop,deadline) || !size || size>kMaxMessage) return false; if (!write) json.resize(size); return Bytes(pipe,json.data(),size,write,stop,deadline); } } std::wstring PipeName() { DWORD session=0; ProcessIdToSessionId(GetCurrentProcessId(),&session); auto sid=UserSid(); if (sid.empty()) return {}; return L"\\\\.\\pipe\\TTDownloader.Browser."+sid+L"."+std::to_wstring(session); } std::string Exchange(const std::string& input,const std::wstring& name) { if (name.empty()) return Serialize(Reply("connection_failed","无法确定当前用户")); Handle pipe(CreateFileW(name.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING, FILE_FLAG_OVERLAPPED|SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr),&CloseHandle); if (pipe.get()==INVALID_HANDLE_VALUE && GetLastError()==ERROR_PIPE_BUSY) { WaitNamedPipeW(name.c_str(),1500); pipe.reset(CreateFileW(name.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING, FILE_FLAG_OVERLAPPED|SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)); } if (pipe.get()==INVALID_HANDLE_VALUE) { DWORD error=GetLastError(); pipe.release(); return Serialize(Reply(error==ERROR_FILE_NOT_FOUND?"client_not_running":"connection_failed", error==ERROR_FILE_NOT_FOUND?"桌面客户端未运行,请先启动 TTDownloader":"桌面客户端繁忙或连接失败")); } ULONGLONG deadline=GetTickCount64()+28000; auto json=input; if (!Frame(pipe.get(),json,true,nullptr,deadline) || !Frame(pipe.get(),json,false,nullptr,deadline)) return Serialize(Reply("connection_failed","桌面通信中断或超时,请检查桌面任务列表")); return json; } PipeServer::PipeServer():stop_(CreateEventW(nullptr,TRUE,FALSE,nullptr)) {} PipeServer::~PipeServer() { Stop(); if (stop_) CloseHandle(stop_); } void PipeServer::Start(Handler handler,std::wstring name) { if (worker_.joinable() || !stop_ || name.empty()) return; ResetEvent(stop_); worker_=std::thread(&PipeServer::Run,this,std::move(handler),std::move(name)); } void PipeServer::Stop() { if (stop_) SetEvent(stop_); if (worker_.joinable()) worker_.join(); } void PipeServer::Run(Handler handler,const std::wstring& name) { auto sid=UserSid(); if (sid.empty()) return; PSECURITY_DESCRIPTOR descriptor=nullptr; auto sddl=L"D:P(A;;GA;;;SY)(A;;GA;;;"+sid+L")"; if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),SDDL_REVISION_1,&descriptor,nullptr)) return; SECURITY_ATTRIBUTES security{sizeof(security),descriptor,FALSE}; Handle pipe(CreateNamedPipeW(name.c_str(),PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED|FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT|PIPE_REJECT_REMOTE_CLIENTS,1,kMaxMessage+4,kMaxMessage+4,1000,&security),&CloseHandle); if (pipe.get()==INVALID_HANDLE_VALUE) { pipe.release(); LocalFree(descriptor); return; } while (WaitForSingleObject(stop_,0)!=WAIT_OBJECT_0) { Handle event(CreateEventW(nullptr,TRUE,FALSE,nullptr),&CloseHandle); if (!event) break; OVERLAPPED operation{}; operation.hEvent=event.get(); DWORD done=0; BOOL connected=ConnectNamedPipe(pipe.get(),&operation); DWORD error=connected?ERROR_SUCCESS:GetLastError(); if (!connected && error==ERROR_IO_PENDING) connected=Complete(pipe.get(),operation,stop_,GetTickCount64()+3600000,done); else if (error==ERROR_PIPE_CONNECTED) connected=TRUE; if (connected && WaitForSingleObject(stop_,0)!=WAIT_OBJECT_0) { std::string json; if (Frame(pipe.get(),json,false,stop_,GetTickCount64()+5000)) { auto response=handler(json,stop_); if (Frame(pipe.get(),response,true,stop_,GetTickCount64()+5000)) { // Let the client consume the response and close before disconnect discards buffers. char closed=0; Bytes(pipe.get(),&closed,1,false,stop_,GetTickCount64()+2000); } } } DisconnectNamedPipe(pipe.get()); } LocalFree(descriptor); } }