137 lines
7.7 KiB
C++
137 lines
7.7 KiB
C++
#include "pipe.h"
|
||
#include "protocol.h"
|
||
#include <sddl.h>
|
||
#include <tlhelp32.h>
|
||
#include <vector>
|
||
#include <memory>
|
||
#include <sstream>
|
||
#include <utility>
|
||
#pragma comment(lib,"advapi32.lib")
|
||
#pragma comment(lib,"user32.lib")
|
||
namespace browser_bridge {
|
||
namespace {
|
||
using Handle=std::unique_ptr<void,decltype(&CloseHandle)>;
|
||
std::wstring UserSid(HANDLE process=GetCurrentProcess()) {
|
||
HANDLE raw=nullptr;
|
||
if (!OpenProcessToken(process,TOKEN_QUERY,&raw)) return {};
|
||
Handle token(raw,&CloseHandle); DWORD size=0;
|
||
GetTokenInformation(token.get(),TokenUser,nullptr,0,&size);
|
||
std::vector<char> buffer(size);
|
||
if (!size || !GetTokenInformation(token.get(),TokenUser,buffer.data(),size,&size)) return {};
|
||
LPWSTR sid=nullptr;
|
||
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER*>(buffer.data())->User.Sid,&sid)) return {};
|
||
std::wstring result(sid); LocalFree(sid); return result;
|
||
}
|
||
bool ClientRunning() {
|
||
if (FindWindowW(L"TTDownloaderMainWindow",nullptr)) return true;
|
||
// A minimized/tray client may belong to another desktop. Match both user and session.
|
||
const auto sid=UserSid(); DWORD session=0;
|
||
if (sid.empty() || !ProcessIdToSessionId(GetCurrentProcessId(),&session)) return false;
|
||
Handle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0),&CloseHandle);
|
||
if (snapshot.get()==INVALID_HANDLE_VALUE) { snapshot.release(); return false; }
|
||
PROCESSENTRY32W entry{}; entry.dwSize=sizeof(entry);
|
||
for (BOOL more=Process32FirstW(snapshot.get(),&entry);more;more=Process32NextW(snapshot.get(),&entry)) {
|
||
if (_wcsicmp(entry.szExeFile,L"ttdownloader.exe") && _wcsicmp(entry.szExeFile,L"ttdownloader_d.exe")) continue;
|
||
DWORD candidateSession=0;
|
||
if (!ProcessIdToSessionId(entry.th32ProcessID,&candidateSession) || candidateSession!=session) continue;
|
||
Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.th32ProcessID),&CloseHandle);
|
||
if (process && UserSid(process.get())==sid) return true;
|
||
}
|
||
return false;
|
||
}
|
||
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<DWORD>(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<char*>(data); DWORD total=0;
|
||
while (total<size) {
|
||
OVERLAPPED operation{}; operation.hEvent=event.get(); ResetEvent(event.get()); DWORD done=0;
|
||
BOOL ok=write?WriteFile(pipe,bytes+total,size-total,&done,&operation):ReadFile(pipe,bytes+total,size-total,&done,&operation);
|
||
if (!ok && (GetLastError()!=ERROR_IO_PENDING || !Complete(pipe,operation,stop,deadline,done))) return false;
|
||
if (!done) return false; total+=done;
|
||
}
|
||
return true;
|
||
}
|
||
bool Frame(HANDLE pipe,std::string& json,bool write,HANDLE stop,ULONGLONG deadline) {
|
||
std::uint32_t size=write?static_cast<std::uint32_t>(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();
|
||
if (error==ERROR_FILE_NOT_FOUND && ClientRunning())
|
||
return Serialize(Reply("client_not_ready",
|
||
"客户端已运行,但浏览器接口未就绪。请完全退出旧客户端(包括托盘),再启动新版 TTDownloader。"));
|
||
return Serialize(Reply(error==ERROR_FILE_NOT_FOUND?"client_not_running":"connection_failed",
|
||
error==ERROR_FILE_NOT_FOUND?"未找到当前用户会话的客户端,请启动新版 TTDownloader":
|
||
"桌面客户端繁忙或连接失败(Windows 错误 "+std::to_string(error)+")"));
|
||
}
|
||
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);
|
||
}
|
||
}
|