新增 Chrome 下载接管扩展与 C++ 本地通信组件

实现链接右键发送、手动地址输入和默认关闭的可选 GET 自动接管,支持站点与文件类型过滤。通过 Native Messaging 和当前用户命名管道在任务入库后确认接管,失败恢复浏览器下载并持久化交接状态。保存请求编号、Referer 与 User-Agent,补充本地注册入口、集成包说明及扩展/stdio/IPC/HTTP 回归测试。
This commit is contained in:
tongtong committed 2026-11-16 15:44:44 +08:00
1 parent 6c810c3b4f
commit 028fec64be
41 files changed
+1081 -18

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
#pragma once
namespace browser_bridge {
inline constexpr char kExtensionOrigin[]="chrome-extension://mlidghkaimgommidibnmcflafblbhcdb/";
inline constexpr char kHostName[]="com.ttstd.ttdownloader";
}
+113
View File
@@ -0,0 +1,113 @@
#include "pipe.h"
#include "protocol.h"
#include <sddl.h>
#include <vector>
#include <memory>
#include <sstream>
#include <utility>
#pragma comment(lib,"advapi32.lib")
namespace browser_bridge {
namespace {
using Handle=std::unique_ptr<void,decltype(&CloseHandle)>;
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<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 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();
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);
}
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <windows.h>
#include <atomic>
#include <functional>
#include <string>
#include <thread>
namespace browser_bridge {
std::wstring PipeName();
std::string Exchange(const std::string& json,const std::wstring& name=PipeName());
class PipeServer {
public:
using Handler=std::function<std::string(const std::string&,HANDLE)>;
PipeServer();
~PipeServer();
void Start(Handler handler,std::wstring name=PipeName());
void Stop();
private:
void Run(Handler,const std::wstring&);
HANDLE stop_=nullptr;
std::thread worker_;
};
}
+122
View File
@@ -0,0 +1,122 @@
#include <windows.h>
#include "protocol.h"
#include <cctype>
#include <set>
namespace browser_bridge {
namespace {
class Parser {
public:
explicit Parser(const std::string& s):s_(s) {}
bool Object(Message& fields) {
Skip(); if (!Take('{')) return false; Skip();
if (Take('}')) { Skip(); return at_==s_.size(); }
do {
std::string key,value;
if (!String(key)) return false; Skip();
if (!Take(':')) return false; Skip();
if (!String(value) || fields.size()>=16 || !fields.emplace(key,value).second) return false;
Skip(); if (Take('}')) { Skip(); return at_==s_.size(); }
if (!Take(',')) return false; Skip();
} while (at_<s_.size());
return false;
}
private:
void Skip() { while (at_<s_.size() && (s_[at_]==' ' || s_[at_]=='\r' || s_[at_]=='\n' || s_[at_]=='\t')) ++at_; }
bool Take(char c) { if (at_>=s_.size() || s_[at_]!=c) return false; ++at_; return true; }
bool Hex(unsigned& value) {
value=0;
for (int i=0;i<4;++i) {
if (at_>=s_.size()) return false;
char c=s_[at_++]; unsigned d;
if (c>='0' && c<='9') d=c-'0'; else if (c>='a' && c<='f') d=c-'a'+10;
else if (c>='A' && c<='F') d=c-'A'+10; else return false;
value=value*16+d;
}
return true;
}
bool String(std::string& value) {
if (!Take('"')) return false;
while (at_<s_.size()) {
unsigned char c=s_[at_++];
if (c=='"') return value.empty() || MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,value.data(),static_cast<int>(value.size()),nullptr,0)>0;
if (c<32) return false;
if (c!='\\') { value.push_back(c); continue; }
if (at_>=s_.size()) return false; c=s_[at_++];
if (c=='"' || c=='\\' || c=='/') value.push_back(c);
else if (c=='b') value+='\b'; else if (c=='f') value+='\f';
else if (c=='n') value+='\n'; else if (c=='r') value+='\r'; else if (c=='t') value+='\t';
else if (c=='u') {
unsigned first,second; if (!Hex(first)) return false;
wchar_t wide[2]={static_cast<wchar_t>(first),0}; int count=1;
if (first>=0xD800 && first<=0xDBFF) {
if (!Take('\\') || !Take('u') || !Hex(second) || second<0xDC00 || second>0xDFFF) return false;
wide[1]=static_cast<wchar_t>(second); count=2;
} else if (first>=0xDC00 && first<=0xDFFF) return false;
char bytes[8]{}; int size=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,wide,count,bytes,8,nullptr,nullptr);
if (!size) return false; value.append(bytes,size);
} else return false;
}
return false;
}
const std::string& s_; size_t at_=0;
};
std::string Quote(const std::string& text) {
constexpr char hex[]="0123456789abcdef"; std::string result="\"";
for (unsigned char c:text) {
if (c=='"' || c=='\\') { result+='\\'; result+=c; }
else if (c<32) { result+="\\u00"; result+=hex[c>>4]; result+=hex[c&15]; }
else result+=c;
}
return result+'"';
}
bool HttpUrl(const std::string& text) {
size_t start=text.rfind("http://",0)==0?7:text.rfind("https://",0)==0?8:0;
if (!start || text.size()>16384 || text.find_first_of("\r\n\t ")!=std::string::npos) return false;
auto end=text.find_first_of("/?#",start);
auto authority=text.substr(start,end==std::string::npos?end:end-start);
return !authority.empty() && authority.find('@')==std::string::npos;
}
}
bool Parse(const std::string& json,Message& fields,std::string& error) {
fields.clear();
if (json.empty() || json.size()>kMaxMessage || !Parser(json).Object(fields)) { error="消息必须是有效的 UTF-8 字符串字段对象"; return false; }
return true;
}
std::string Serialize(const Message& fields) {
std::string json="{";
for (const auto& [key,value]:fields) { if (json.size()>1) json+=','; json+=Quote(key)+':'+Quote(value); }
return json+'}';
}
std::string Get(const Message& fields,const std::string& key) { auto it=fields.find(key); return it==fields.end()?"":it->second; }
bool Validate(const Message& fields,std::string& error) {
static const std::set<std::string> allowed={"action","request_id","url","referrer","user_agent","filename","method"};
for (const auto& [key,value]:fields) {
if (!allowed.count(key) || value.find('\0')!=std::string::npos) { error="不支持的字段"; return false; }
for (unsigned char c:value) if (c<32 || c==127) { error="字段不能含控制字符"; return false; }
}
const auto action=Get(fields,"action"),id=Get(fields,"request_id");
if (id.empty() || id.size()>80) { error="请求编号无效"; return false; }
for (unsigned char c:id) if (!std::isalnum(c) && c!='-') { error="请求编号无效"; return false; }
if (action=="ping" && fields.size()<=2) return true;
if (action!="add" || Get(fields,"method")!="GET" || !HttpUrl(Get(fields,"url"))
|| (!Get(fields,"referrer").empty() && !HttpUrl(Get(fields,"referrer")))
|| Get(fields,"user_agent").size()>2048 || Get(fields,"filename").size()>1024) {
error="仅支持 HTTP/HTTPS GET 下载地址及合法上下文"; return false;
}
return true;
}
bool ReadFrame(std::istream& input,std::string& json) {
unsigned char b[4]; if (!input.read(reinterpret_cast<char*>(b),4)) return false;
std::uint32_t n=b[0]|(static_cast<std::uint32_t>(b[1])<<8)|(static_cast<std::uint32_t>(b[2])<<16)|(static_cast<std::uint32_t>(b[3])<<24);
if (!n || n>kMaxMessage) return false;
json.resize(n); return static_cast<bool>(input.read(json.data(),n));
}
bool WriteFrame(std::ostream& output,const std::string& json) {
if (json.empty() || json.size()>kMaxMessage) return false;
auto n=static_cast<std::uint32_t>(json.size()); unsigned char b[4]={static_cast<unsigned char>(n),static_cast<unsigned char>(n>>8),static_cast<unsigned char>(n>>16),static_cast<unsigned char>(n>>24)};
output.write(reinterpret_cast<char*>(b),4); output.write(json.data(),json.size()); output.flush(); return static_cast<bool>(output);
}
Message Reply(const std::string& status,const std::string& message,const std::string& id,const std::string& task) {
return {{"status",status},{"message",message},{"request_id",id},{"task_id",task}};
}
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <cstdint>
#include <istream>
#include <ostream>
#include <map>
#include <string>
namespace browser_bridge {
inline constexpr std::uint32_t kMaxMessage=64*1024;
using Message=std::map<std::string,std::string>;
bool Parse(const std::string&,Message&,std::string& error);
std::string Serialize(const Message&);
bool Validate(const Message&,std::string& error);
std::string Get(const Message&,const std::string& key);
bool ReadFrame(std::istream&,std::string&);
bool WriteFrame(std::ostream&,const std::string&);
Message Reply(const std::string& status,const std::string& message,const std::string& request_id="",const std::string& task_id="");
}