Files
TTDownloader/browser/native/main.cpp
T

115 lines
7.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "../shared/protocol.h"
#include "../shared/pipe.h"
#include "../shared/identity.h"
#include "client_connection.h"
#include "../shared/command_line.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;
}
std::string LaunchClient(const browser_bridge::Message& request) {
using namespace browser_bridge;
// Launch a fixed sibling. Validated browser data is one argv value, never shell code.
std::vector<wchar_t> module(32768);
DWORD size=GetModuleFileNameW(nullptr,module.data(),static_cast<DWORD>(module.size()));
if (!size || size>=module.size()) return Serialize(Reply("launch_failed","无法确定客户端安装目录"));
std::wstring path(module.data()); auto slash=path.find_last_of(L"\\/");
const auto directory=path.substr(0,slash);
const bool debug=path.substr(slash+1)==L"ttdownloader_native_host_d.exe";
path=directory+(debug?L"\\ttdownloader_d.exe":L"\\ttdownloader.exe");
const auto json=Serialize(request);
int length=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,json.data(),static_cast<int>(json.size()),nullptr,0);
if (!length) return Serialize(Reply("launch_failed","启动参数不是有效 UTF-8"));
std::wstring payload(length,L'\0');
MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,json.data(),static_cast<int>(json.size()),payload.data(),length);
std::wstring command=QuoteArgument(path)+L" --browser-request "+QuoteArgument(payload);
if (command.size()>=32767) return Serialize(Reply("launch_failed","下载地址和上下文过长,请先手动启动客户端"));
STARTUPINFOW startup{sizeof(startup)}; PROCESS_INFORMATION process{};
startup.dwFlags=STARTF_USESHOWWINDOW; startup.wShowWindow=SW_SHOWNORMAL;
if (!CreateProcessW(path.c_str(),command.data(),nullptr,nullptr,FALSE,0,nullptr,directory.c_str(),&startup,&process))
return Serialize(Reply("launch_failed","无法启动 TTDownloader(Windows 错误 "+std::to_string(GetLastError())+"),请检查安装目录"));
CloseHandle(process.hThread); CloseHandle(process.hProcess);
return {};
}
std::string WaitForClient(const std::string& ping) {
using namespace browser_bridge;
Message reply; std::string error;
const auto deadline=GetTickCount64()+10000;
do {
Sleep(100); auto probe=Exchange(ping);
if (Parse(probe,reply,error) && Get(reply,"status")=="ready") return probe;
if (Get(reply,"status")!="client_not_running" && Get(reply,"status")!="client_not_ready") return probe;
} while (GetTickCount64()<deadline);
return Serialize(Reply("client_not_ready","客户端未能就绪,请完全退出旧版后启动新版,再发送下载地址"));
}
std::string SendToClient(const browser_bridge::Message& request,const std::string& json) {
return browser_bridge::ForwardToClient(request,json,
[](const std::string& value) { return browser_bridge::Exchange(value); },[&] { return LaunchClient(request); },WaitForClient);
}
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=SendToClient(fields,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;
}