Files
TTDownloader/browser/native/main.cpp
T
tongtong 028fec64be 新增 Chrome 下载接管扩展与 C++ 本地通信组件
实现链接右键发送、手动地址输入和默认关闭的可选 GET 自动接管,支持站点与文件类型过滤。通过 Native Messaging 和当前用户命名管道在任务入库后确认接管,失败恢复浏览器下载并持久化交接状态。保存请求编号、Referer 与 User-Agent,补充本地注册入口、集成包说明及扩展/stdio/IPC/HTTP 回归测试。
2026-11-16 15:44:44 +08:00

74 lines
4.7 KiB
C++

#include "../shared/protocol.h"
#include "../shared/pipe.h"
#include "../shared/identity.h"
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <vector>
namespace {
std::string Utf8(const std::wstring& value) {
int size=WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast<int>(value.size()),nullptr,0,nullptr,nullptr);
std::string text(size,0); WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast<int>(value.size()),text.data(),size,nullptr,nullptr); return text;
}
int RegisterHost(const std::string& browser,bool remove) {
if (browser!="chrome" && browser!="edge" && browser!="both") { std::cerr<<"Expected chrome, edge or both\n"; return 1; }
std::vector<wchar_t> executable(32768),local(32768);
DWORD n=GetModuleFileNameW(nullptr,executable.data(),static_cast<DWORD>(executable.size()));
DWORD m=GetEnvironmentVariableW(L"LOCALAPPDATA",local.data(),static_cast<DWORD>(local.size()));
if (!n || n>=executable.size() || !m || m>=local.size()) return 1;
std::wstring directory=std::wstring(local.data())+L"\\TTDownloader",manifest=directory+L"\\native_host.json";
if (!remove) {
if (!CreateDirectoryW(directory.c_str(),nullptr) && GetLastError()!=ERROR_ALREADY_EXISTS) return 1;
auto json=browser_bridge::Serialize({{"name",browser_bridge::kHostName},{"description","TTDownloader native download bridge"},{"path",Utf8(executable.data())},{"type","stdio"}});
json.pop_back(); json+=",\"allowed_origins\":[\""+std::string(browser_bridge::kExtensionOrigin)+"\"]}";
HANDLE file=CreateFileW(manifest.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);
if (file==INVALID_HANDLE_VALUE) return 1;
DWORD written=0; bool ok=WriteFile(file,json.data(),static_cast<DWORD>(json.size()),&written,nullptr) && written==json.size();
CloseHandle(file); if (!ok) return 1;
}
for (const auto& target : {std::string("chrome"),std::string("edge")}) {
if (browser!="both" && browser!=target) continue;
auto key=std::wstring(target=="chrome"?L"Software\\Google\\Chrome\\NativeMessagingHosts\\":L"Software\\Microsoft\\Edge\\NativeMessagingHosts\\")+L"com.ttstd.ttdownloader";
if (remove) {
LSTATUS status=RegDeleteKeyExW(HKEY_CURRENT_USER,key.c_str(),KEY_WOW64_32KEY,0);
if (status!=ERROR_SUCCESS && status!=ERROR_FILE_NOT_FOUND) return 1;
} else {
HKEY handle=nullptr;
if (RegCreateKeyExW(HKEY_CURRENT_USER,key.c_str(),0,nullptr,0,KEY_SET_VALUE|KEY_WOW64_32KEY,nullptr,&handle,nullptr)!=ERROR_SUCCESS) return 1;
LSTATUS status=RegSetValueExW(handle,nullptr,0,REG_SZ,reinterpret_cast<const BYTE*>(manifest.c_str()),static_cast<DWORD>((manifest.size()+1)*sizeof(wchar_t)));
RegCloseKey(handle); if (status!=ERROR_SUCCESS) return 1;
}
}
std::cout<<(remove?"Unregistered":"Registered")<<" TTDownloader Native Messaging Host for "<<browser<<".\n"; return 0;
}
}
int main(int argc,char** argv) {
if (argc>=2 && (std::string(argv[1])=="--register" || std::string(argv[1])=="--unregister")) {
int result=RegisterHost(argc>=3?argv[2]:"chrome",std::string(argv[1])=="--unregister");
if (result) std::cerr<<"Native host registration failed. Check the application path and current-user registry access.\n";
return result;
}
if (argc<2 || std::string(argv[1])!=browser_bridge::kExtensionOrigin) return 1;
_setmode(_fileno(stdin),_O_BINARY); _setmode(_fileno(stdout),_O_BINARY);
std::ios::sync_with_stdio(false);
std::string json;
while (browser_bridge::ReadFrame(std::cin,json)) {
browser_bridge::Message fields; std::string error,response;
if (!browser_bridge::Parse(json,fields,error) || !browser_bridge::Validate(fields,error))
response=browser_bridge::Serialize(browser_bridge::Reply("invalid_request",error,browser_bridge::Get(fields,"request_id")));
else {
response=browser_bridge::Exchange(json);
browser_bridge::Message reply;
const auto expected=browser_bridge::Get(fields,"request_id");
if (!browser_bridge::Parse(response,reply,error) || browser_bridge::Get(reply,"status").empty()
|| (!browser_bridge::Get(reply,"request_id").empty() && browser_bridge::Get(reply,"request_id")!=expected)
|| (browser_bridge::Get(reply,"status")=="accepted" && browser_bridge::Get(reply,"request_id")!=expected))
reply=browser_bridge::Reply("connection_failed","桌面返回无效消息或请求编号不匹配");
reply["request_id"]=expected;
response=browser_bridge::Serialize(reply);
}
if (!browser_bridge::WriteFrame(std::cout,response)) return 1;
}
return 0;
}