新增 Chrome 下载接管扩展与 C++ 本地通信组件
实现链接右键发送、手动地址输入和默认关闭的可选 GET 自动接管,支持站点与文件类型过滤。通过 Native Messaging 和当前用户命名管道在任务入库后确认接管,失败恢复浏览器下载并持久化交接状态。保存请求编号、Referer 与 User-Agent,补充本地注册入口、集成包说明及扩展/stdio/IPC/HTTP 回归测试。
This commit is contained in:
1 parent
6c810c3b4f
commit
028fec64be
41 files changed
+1081
-18
No files matched your search
@@ -27,3 +27,7 @@ Desktop.ini
|
||||
# TTUI build output
|
||||
ui/ttui/lib/
|
||||
ui/ttui/obj/
|
||||
|
||||
# Browser host intermediates
|
||||
browser/native/obj/
|
||||
browser/tests/obj/
|
||||
@@ -34,6 +34,16 @@
|
||||
- 桌面端未运行、通信失败或任务重复时,应向用户提供明确状态,不得静默丢任务。
|
||||
- 不默认拦截浏览器全部下载;自动接管、站点规则和过滤策略应可配置。
|
||||
|
||||
## 浏览器插件当前实现
|
||||
|
||||
- `browser/chrome/` 为 Chrome/Edge Manifest V3 扩展,包含链接右键发送、手动地址输入、默认关闭的自动接管,以及站点/文件类型过滤。
|
||||
- `browser/native/` 为 C++ Native Messaging Host,使用固定扩展公钥对应的 allowed_origins;不得向 stdout 输出协议帧以外的日志。消息为最多 64KiB 的 UTF-8 字符串字段对象。
|
||||
- `browser/shared/` 为受当前用户 ACL 和会话隔离保护的本地命名管道。IPC 在独立线程执行,任务校验和 SQLite 入库仍由下载引擎线程完成。
|
||||
- 自动接管仅处理观察到的 HTTP/HTTPS GET 下载;先记录恢复状态、暂停浏览器、等待任务入库确认,再取消浏览器下载。重复、离线、通信失败时恢复浏览器,后台重启须恢复未完成交接,不能把恢复状态只放在内存中。
|
||||
- 浏览器上下文仅包含 Referer、User-Agent 和文件名提示;首版不传 Cookie、认证信息、POST 请求体或 blob/data 数据。Referer 和 User-Agent 通过 TaskStore 保存,恢复下载仍须沿用,所有请求头拒绝控制字符。
|
||||
- 请求编号随任务保存,重试相同请求编号不得重复创建任务;明确区分 accepted、duplicate、rejected、client_not_running、client_not_ready 和通信失败。
|
||||
- Host 注册必须由用户执行 `browser/register-host.cmd`(当前用户注册,无需管理员);编译、测试不能自动安装扩展或修改用户浏览器配置。新功能需同时更新本地 IPC/stdio、恢复状态机和 HTTP 上下文回归测试。
|
||||
|
||||
## HTTP 传输层边界
|
||||
|
||||
- `client/src/http_transport.h` 定义不含 Windows/WinHTTP 原生句柄的请求、响应和同步流接口;传输层不依赖 TaskInfo、TaskStore、窗口或下载任务命令。
|
||||
|
||||
@@ -6,6 +6,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ttdownloader", "client\ttdo
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ttui", "ui\ttui\ttui.vcxproj", "{19F8F655-C0F5-4AD9-B999-58D23F95AB43}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "native_host", "browser\native\native_host.vcxproj", "{F8C0CDE7-9F20-4D81-A472-73BA1F151505}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
@@ -20,6 +22,10 @@ Global
|
||||
{19F8F655-C0F5-4AD9-B999-58D23F95AB43}.Debug|x64.Build.0 = Debug|x64
|
||||
{19F8F655-C0F5-4AD9-B999-58D23F95AB43}.Release|x64.ActiveCfg = Release|x64
|
||||
{19F8F655-C0F5-4AD9-B999-58D23F95AB43}.Release|x64.Build.0 = Release|x64
|
||||
{F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Debug|x64.Build.0 = Debug|x64
|
||||
{F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Release|x64.ActiveCfg = Release|x64
|
||||
{F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# TTDownloader 浏览器下载接管
|
||||
|
||||
Chrome Manifest V3 扩展 + 全 C++ Native Messaging Host + 桌面下载引擎。Edge 可加载同一扩展目录。
|
||||
|
||||
## 安装 Chrome 版本
|
||||
|
||||
1. 源码用户先在仓库根目录运行 `build.cmd Release`;打包版本已附带可执行文件。编译得到 `client/bin/ttdownloader.exe` 与 `client/bin/ttdownloader_native_host.exe`。先退出旧客户端,再启动新版本。
|
||||
2. 运行 `browser/register-host.cmd`,将 Host 注册到当前用户 Chrome 的 NativeMessagingHosts(32 位注册表视图)。无需管理员、不依赖 PowerShell;Host 配置写入 `%LOCALAPPDATA%/TTDownloader/native_host.json`。
|
||||
3. 打开 Chrome 的 `chrome://extensions`,启用开发者模式,选择“加载已解压的扩展程序”,选中 `browser/chrome/`。
|
||||
4. 点击扩展按钮,选择“检查桌面连接”。扩展 ID 由 manifest 中的固定公开 key 决定,必须与 Host 的 allowed_origins 一致;不要删除或改写 key。
|
||||
|
||||
卸载本地注册:运行 `browser/unregister-host.cmd`。它只移除当前用户注册项,保留客户端、下载文件和任务数据库。移动 Host 后需重新注册。
|
||||
|
||||
Edge:在 `edge://extensions` 加载同一目录,并执行 `client/bin/ttdownloader_native_host.exe --register edge`;也可以用 `--register both` 同时注册。卸载对应使用 `--unregister edge/both`。
|
||||
|
||||
## 使用方式
|
||||
|
||||
- 右键点击 HTTP/HTTPS 链接,选择“使用 TTDownloader 下载”。
|
||||
- 在扩展弹窗粘贴下载地址后发送。客户端接收并入库后显示成功;重复会明确显示已有任务。
|
||||
- 默认不自动接管。勾选“自动接管”,保存时按 Chrome 提示授予可选站点访问与 webRequest 权限。可指定站点和文件类型;留空表示不限制。
|
||||
- 站点以空格或逗号分隔,支持 `example.com` 精确匹配和 `*.example.com` 子域匹配。文件类型如 `.zip,.exe,.mp4`,按文件名或 URL 路径后缀匹配。
|
||||
|
||||
自动接管先将恢复记录写入扩展本地存储,再暂停浏览器下载。桌面任务入库确认后才取消浏览器下载。通信失败、客户端未启动或重复任务会保留/恢复浏览器下载。失败会显示通知、工具栏 `!` 和弹窗状态。后台重启时重用同一个请求编号,避免重复创建桌面任务;已恢复的浏览器任务不会再次被暂停。
|
||||
|
||||
桌面客户端需已启动,首版不自动启动客户端。入库确认代表任务已交给桌面引擎,并不代表目标服务器已经返回下载内容。
|
||||
|
||||
## 支持范围
|
||||
|
||||
- 仅 HTTP/HTTPS GET;自动接管要求最近观察到 GET 请求。POST、blob/data、其他扩展创建的下载、隐身下载、浏览器标记的危险下载、用户已暂停的下载和无法确认请求方法的下载留在浏览器。
|
||||
- 提交 Referer、User-Agent、文件名提示和请求编号。自动接管使用浏览器提供的 Referer;手动链接跨站只传来源 origin,HTTPS 降级不传来源。文件名只取 basename 并经过客户端清理,不接受浏览器指定任意保存路径;下载目录由桌面端决定。
|
||||
- 不读取或转发 Cookie、登录凭据或 POST 内容。依赖登录态、一次性请求或特殊认证的网站可能仍需浏览器下载,应从自动规则中排除。
|
||||
- 不处理视频网站解析、BT 或磁力链接。
|
||||
- 扩展使用 Chrome 109 及以上 API;桌面 Host 以 Windows 7 SP1 x64 为兼容目标。当前通过构建及协议自动化测试,尚未在真实 Chrome/Edge 加载或 Windows 7 虚拟机完成验收。
|
||||
|
||||
## 结构与边界
|
||||
|
||||
`扩展 → Native Messaging Host → 当前用户/当前会话命名管道 → 下载引擎命令队列 → TaskStore`。
|
||||
|
||||
Host 限制扩展来源和 64KiB 消息长度,按原生消息协议使用 4 字节小端长度 + UTF-8 JSON,stdout 不输出普通日志。IPC 限制当前用户与 SYSTEM,拒绝远程连接。未安装、客户端未启动、繁忙、重复或失败都有单独状态。
|
||||
|
||||
任务只在引擎线程中访问数据库。新增 request_id/referrer/user_agent 列由 TaskStore 对旧库逐列补齐;恢复后保留必要上下文。浏览器请求错误不会误关闭桌面手动添加窗口。
|
||||
|
||||
## 测试
|
||||
|
||||
运行 `test.cmd Debug` / `test.cmd Release`,需要开发机安装 Node.js 20+ 和 Python,客户端运行不依赖它们。
|
||||
|
||||
覆盖扩展过滤、确认前不取消、离线/重复/断线恢复、恢复失败、后台重启、用户恢复下载、实际后台事件接线;Native Host UTF-8/帧长度/来源校验;用户隔离命名管道与取消 I/O;临时 SQLite 上下文保存恢复;HTTP Referer/User-Agent 发送和头注入拒绝。测试不安装扩展、不修改用户注册表、不向真实任务库添加下载。
|
||||
|
||||
协议参考:[Chrome Native Messaging](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging)、[downloads API](https://developer.chrome.com/docs/extensions/reference/api/downloads)、[contextMenus API](https://developer.chrome.com/docs/extensions/reference/api/contextMenus)。
|
||||
@@ -0,0 +1,88 @@
|
||||
import {DEFAULTS, httpUrl, eligible, linkReferrer, requestFor, handoff, recover} from './logic.mjs';
|
||||
const HOST = 'com.ttstd.ttdownloader';
|
||||
const observed = new Map(), busy = new Set();
|
||||
let recovery = null;
|
||||
const config = async () => ({...DEFAULTS, ...(await chrome.storage.local.get('config')).config});
|
||||
async function status(result) {
|
||||
await chrome.storage.local.set({lastResult: {...result, time: Date.now()}});
|
||||
const ok = ['accepted', 'ready'].includes(result.status);
|
||||
await chrome.action.setBadgeText({text: ok ? 'OK' : '!'});
|
||||
await chrome.action.setBadgeBackgroundColor({color: ok ? '#247a48' : '#af4d00'});
|
||||
await chrome.action.setTitle({title: 'TTDownloader:' + result.message});
|
||||
if (!ok && result.status !== 'duplicate') chrome.notifications.create({type: 'basic', iconUrl: 'icon.png', title: 'TTDownloader 下载接管', message: result.message}, () => { void chrome.runtime.lastError; });
|
||||
return result;
|
||||
}
|
||||
function native(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let port, timer, finished = false;
|
||||
const done = (error, value) => { if (finished) return; finished = true; clearTimeout(timer); port?.disconnect(); error ? reject(error) : resolve(value); };
|
||||
try {
|
||||
port = chrome.runtime.connectNative(HOST);
|
||||
port.onMessage.addListener(reply => {
|
||||
if (reply?.request_id !== request.request_id) return done(new Error('本地响应编号不匹配,请检查桌面任务列表'));
|
||||
done(null, reply);
|
||||
});
|
||||
port.onDisconnect.addListener(() => done(new Error('本地组件未连接:' + (chrome.runtime.lastError?.message || '通信中断') + ';请检查注册和桌面客户端')));
|
||||
timer = setTimeout(() => done(new Error('本地通信超时,请检查桌面任务列表')), 30000);
|
||||
port.postMessage(request);
|
||||
} catch (error) { done(error); }
|
||||
});
|
||||
}
|
||||
const requestObserver = details => {
|
||||
const url = httpUrl(details.url); if (!url) return;
|
||||
observed.set(url, {method: details.method, time: Date.now()});
|
||||
if (observed.size > 512) observed.delete(observed.keys().next().value);
|
||||
};
|
||||
async function configure() {
|
||||
if (chrome.webRequest?.onBeforeRequest.hasListener(requestObserver)) chrome.webRequest.onBeforeRequest.removeListener(requestObserver);
|
||||
const allowed = await chrome.permissions.contains({permissions: ['webRequest'], origins: ['http://*/*', 'https://*/*']});
|
||||
const settings = await config();
|
||||
if (settings.auto && !allowed) { await chrome.storage.local.set({config: {...settings, auto: false}}); await status({status: 'error', message: '站点权限未授予或已撤销,自动接管已停用'}); }
|
||||
if (settings.auto && allowed) chrome.webRequest.onBeforeRequest.addListener(requestObserver, {urls: ['http://*/*', 'https://*/*']});
|
||||
else observed.clear();
|
||||
}
|
||||
async function restorePending() {
|
||||
if (recovery || busy.size) return recovery;
|
||||
recovery = (async () => { for (const outcome of await recover(chrome, native, (await config()).auto)) await status(outcome); })()
|
||||
.catch(error => status({status: 'error', message: '恢复下载状态失败:' + error.message})).finally(() => { recovery = null; });
|
||||
return recovery;
|
||||
}
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
chrome.contextMenus.removeAll(() => chrome.contextMenus.create({id: 'send', title: '使用 TTDownloader 下载', contexts: ['link'], targetUrlPatterns: ['http://*/*', 'https://*/*']}));
|
||||
chrome.alarms.create('recover', {periodInMinutes: 1}); configure().catch(console.error);
|
||||
});
|
||||
chrome.runtime.onStartup.addListener(() => { configure().catch(console.error); restorePending(); });
|
||||
chrome.alarms.onAlarm.addListener(alarm => { if (alarm.name === 'recover') restorePending(); });
|
||||
chrome.permissions.onAdded.addListener(() => configure().catch(console.error));
|
||||
chrome.permissions.onRemoved.addListener(() => configure().catch(console.error));
|
||||
chrome.storage.onChanged.addListener(changes => { if (changes.config) { configure().catch(console.error); restorePending(); } });
|
||||
chrome.contextMenus.onClicked.addListener(async info => {
|
||||
if (info.menuItemId !== 'send') return;
|
||||
try { await status(await native(requestFor(info.linkUrl, linkReferrer(info.pageUrl, info.linkUrl)))); }
|
||||
catch (error) { await status({status: 'error', message: error.message}); }
|
||||
});
|
||||
chrome.downloads.onCreated.addListener(async item => {
|
||||
if (recovery) await recovery;
|
||||
const url = httpUrl(item.finalUrl || item.url);
|
||||
if (!eligible(item, await config(), observed.get(url) || observed.get(httpUrl(item.url))) || busy.has(item.id)) return;
|
||||
busy.add(item.id);
|
||||
try { await status(await handoff(chrome, item, requestFor(url, item.referrer, item.filename || ''), native)); }
|
||||
catch (error) { await status({status: 'error', message: '接管失败,请在下载页检查任务:' + error.message}); }
|
||||
finally { busy.delete(item.id); }
|
||||
});
|
||||
chrome.runtime.onMessage.addListener((message, sender, respond) => {
|
||||
if (sender.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(''))) return;
|
||||
(async () => {
|
||||
try {
|
||||
if (message.action === 'ping') return await status(await native({action: 'ping', request_id: crypto.randomUUID()}));
|
||||
if (message.action === 'send') return await status(await native(requestFor(message.url)));
|
||||
return {status: 'error', message: '不支持的操作'};
|
||||
} catch (error) { return status({status: 'error', message: error.message}); }
|
||||
})().then(respond);
|
||||
return true;
|
||||
});
|
||||
// Register synchronously so MV3 can deliver the first request after a worker restart.
|
||||
try { chrome.webRequest?.onBeforeRequest.addListener(requestObserver, {urls: ['http://*/*', 'https://*/*']}); } catch {}
|
||||
chrome.alarms.create('recover', {periodInMinutes: 1});
|
||||
configure().catch(console.error);
|
||||
restorePending();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 491 B |
@@ -0,0 +1,88 @@
|
||||
export const DEFAULTS = Object.freeze({auto: false, sites: '', extensions: ''});
|
||||
export function httpUrl(value) {
|
||||
try { const u = new URL(value); if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) return ''; u.hash = ''; return u.href; } catch { return ''; }
|
||||
}
|
||||
export function eligible(item, config, observed, now = Date.now()) {
|
||||
if (!config.auto || item.state !== 'in_progress' || item.paused || item.incognito || item.byExtensionId || (item.danger && item.danger !== 'safe')) return false;
|
||||
const url = httpUrl(item.finalUrl || item.url);
|
||||
if (!url || !observed || observed.method !== 'GET' || now - observed.time > 15000) return false;
|
||||
const parsed = new URL(url);
|
||||
const sites = config.sites.split(/[\s,]+/).filter(Boolean).map(s => s.toLowerCase());
|
||||
if (sites.length && !sites.some(s => s.startsWith('*.') ? parsed.hostname.endsWith(s.slice(1)) : parsed.hostname === s)) return false;
|
||||
const types = config.extensions.toLowerCase().split(/[\s,]+/).filter(Boolean).map(s => s.startsWith('.') ? s : '.' + s);
|
||||
const name = (item.filename || parsed.pathname).toLowerCase();
|
||||
return !types.length || types.some(type => name.endsWith(type));
|
||||
}
|
||||
export function linkReferrer(source, target) {
|
||||
const from = httpUrl(source), to = httpUrl(target); if (!from || !to) return '';
|
||||
const a = new URL(from), b = new URL(to);
|
||||
if (a.protocol === 'https:' && b.protocol === 'http:') return '';
|
||||
return a.origin === b.origin ? a.href : a.origin + '/';
|
||||
}
|
||||
export function requestFor(url, referrer = '', filename = '') {
|
||||
const normalized = httpUrl(url); if (!normalized) throw new Error('仅支持不含账号密码的 HTTP/HTTPS 下载地址');
|
||||
return {action: 'add', request_id: crypto.randomUUID(), method: 'GET', url: normalized,
|
||||
referrer: httpUrl(referrer), filename: filename.split(/[\\/]/).pop().slice(0, 240), user_agent: navigator.userAgent};
|
||||
}
|
||||
const key = id => `pending_${id}`;
|
||||
const save = (api, record) => api.storage.local.set({[key(record.id)]: record});
|
||||
const remove = (api, id) => api.storage.local.remove(key(id));
|
||||
const current = async (api, id) => (await api.downloads.search({id}))[0];
|
||||
async function restore(api, record, message) {
|
||||
record.phase = 'resume';
|
||||
try { await save(api, record); } catch {} // Recovery must still resume when storage is temporarily unavailable.
|
||||
try {
|
||||
const item = await current(api, record.id);
|
||||
if (item?.state === 'in_progress' && item.paused) await api.downloads.resume(record.id);
|
||||
try { await remove(api, record.id); } catch {}
|
||||
return {status: 'fallback', message: message + ';已保留或恢复浏览器下载'};
|
||||
} catch {
|
||||
return {status: 'recovery_pending', message: message + ';恢复失败,已保留恢复记录,请在浏览器下载页继续下载'};
|
||||
}
|
||||
}
|
||||
async function finish(api, record) {
|
||||
try {
|
||||
const item = await current(api, record.id);
|
||||
if (item?.state === 'in_progress' && !item.paused) {
|
||||
await remove(api, record.id);
|
||||
return {status: 'warning', message: '桌面已接收任务,但浏览器下载已被恢复;请检查是否重复下载'};
|
||||
}
|
||||
if (item?.state === 'in_progress') await api.downloads.cancel(record.id);
|
||||
await remove(api, record.id);
|
||||
return {status: 'accepted', message: '已交给 TTDownloader,任务编号 ' + record.task_id};
|
||||
} catch {
|
||||
return {status: 'recovery_pending', message: '桌面已接收任务,浏览器取消失败,将继续重试'};
|
||||
}
|
||||
}
|
||||
export async function handoff(api, item, request, sendNative, saved = null) {
|
||||
const record = saved || {id: item.id, request, phase: 'pause', created: Date.now(), original: httpUrl(item.finalUrl || item.url)};
|
||||
if (record.phase === 'cancel') return finish(api, record);
|
||||
if (record.phase === 'resume') return restore(api, record, '继续恢复浏览器下载');
|
||||
try {
|
||||
// Journal intent before pausing, so a service-worker restart cannot strand a paused task.
|
||||
await save(api, record);
|
||||
if (!item.paused) await api.downloads.pause(item.id);
|
||||
record.phase = 'sending'; await save(api, record);
|
||||
const reply = await sendNative(record.request);
|
||||
if (reply?.status !== 'accepted' || reply.request_id !== request.request_id || typeof reply.task_id !== 'string' || !/^[1-9][0-9]{0,18}$/.test(reply.task_id))
|
||||
return restore(api, record, reply?.message || '桌面未确认接管');
|
||||
record.phase = 'cancel'; record.task_id = reply.task_id; await save(api, record);
|
||||
return finish(api, record);
|
||||
} catch (error) {
|
||||
return restore(api, record, error.message || '本地通信失败,结果未确认');
|
||||
}
|
||||
}
|
||||
export async function recover(api, sendNative, auto) {
|
||||
const values = await api.storage.local.get(null), outcomes = [];
|
||||
for (const record of Object.values(values).filter(v => v && v.request && Number.isInteger(v.id) && v.phase)) {
|
||||
const item = await current(api, record.id);
|
||||
if (!item || httpUrl(item.finalUrl || item.url) !== record.original || item.state !== 'in_progress') { await remove(api, record.id); continue; }
|
||||
if (record.phase === 'sending' && !item.paused) {
|
||||
await remove(api, record.id); outcomes.push({status: 'warning', message: '浏览器下载已恢复,已停止重复接管;请核对桌面任务列表'}); continue;
|
||||
}
|
||||
if (record.phase === 'cancel') outcomes.push(await finish(api, record));
|
||||
else if (!auto || Date.now() - record.created > 120000 || record.phase === 'resume') outcomes.push(await restore(api, record, '接管未完成'));
|
||||
else outcomes.push(await handoff(api, item, record.request, sendNative, record));
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "TTDownloader 下载接管",
|
||||
"description": "将主动发起的 HTTP/HTTPS 下载交给 TTDownloader,自动接管默认关闭。",
|
||||
"version": "0.1.0",
|
||||
"minimum_chrome_version": "109",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvbbxlyA8oQYALtekWYplS8AuRDPyQmQX51/zpbfYT10Zpsbs+8yd0/l4aP9ByJyjs0N3oI0EsFcA6FPqWK+/SPDeMqZiyxSiIGzcy+zCjYiKelUSzBz80gayXk6R509YV2GKbpt9LOliK92GQy+bacblVScXtqKqmjrubTo+WplRXnPjS0pv2Kx7saSyX10ajjsOTmg1kNaN3x1tCbkOSXR+46idt5VC78sSvixfqwdD0tIqcH7TI6jN0t3nvQakFgfYlcjAgAJrC1PYZdoZMAT2dOjyXV73Bf2y7NHvRQtkDj37Cm88AOH6FncvME7zUbiGrfmZx+ik+rdBQHUULQIDAQAB",
|
||||
"permissions": [
|
||||
"nativeMessaging",
|
||||
"contextMenus",
|
||||
"storage",
|
||||
"downloads",
|
||||
"alarms",
|
||||
"notifications"
|
||||
],
|
||||
"optional_permissions": [
|
||||
"webRequest"
|
||||
],
|
||||
"optional_host_permissions": [
|
||||
"http://*/*",
|
||||
"https://*/*"
|
||||
],
|
||||
"background": {
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"action": {
|
||||
"default_popup": "popup.html",
|
||||
"default_title": "TTDownloader"
|
||||
},
|
||||
"icons": {
|
||||
"128": "icon.png"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
body{width:340px;margin:18px;font:14px "Microsoft YaHei",sans-serif;color:#273449;background:#f0f3f8}h1{font-size:20px}form{border-top:1px solid #bbc8d8;margin-top:16px;padding-top:14px}label{display:block;margin:10px 0 6px}input:not([type=checkbox]),textarea{box-sizing:border-box;width:100%;padding:8px;border:1px solid #9aabc0;border-radius:3px}button{padding:8px 12px;margin-top:8px;border:1px solid #307ef3;color:#245cb0;background:transparent;border-radius:3px;cursor:pointer}button:disabled{opacity:.5;cursor:wait}#status{overflow-wrap:anywhere;white-space:pre-line}.note{color:#64748b;font-size:12px;line-height:1.6}
|
||||
@@ -0,0 +1,5 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>TTDownloader</title><link rel="stylesheet" href="popup.css">
|
||||
<body><h1>TTDownloader</h1><p id="status" role="status">正在读取状态…</p><button id="ping">检查桌面连接</button>
|
||||
<form id="send"><label for="url">下载地址</label><input id="url" type="url" placeholder="https://…" required><button>交给 TTDownloader</button></form>
|
||||
<form id="settings"><label><input id="auto" type="checkbox"> 自动接管已确认的 GET 下载</label><label for="sites">站点规则(留空表示全部)</label><textarea id="sites" placeholder="example.com, *.example.org"></textarea><label for="extensions">文件类型(留空表示全部)</label><input id="extensions" placeholder=".zip, .exe, .mp4"><button>保存接管设置</button></form>
|
||||
<p class="note">也可右键点击链接发送。自动接管默认关闭;失败会恢复浏览器下载。首版不接管 POST、blob、登录 Cookie 或无法确认方法的下载。</p><script type="module" src="popup.js"></script></body></html>
|
||||
@@ -0,0 +1,25 @@
|
||||
import {DEFAULTS} from './logic.mjs';
|
||||
const el = id => document.getElementById(id);
|
||||
const cfg = {...DEFAULTS, ...(await chrome.storage.local.get('config')).config};
|
||||
for (const field of ['sites', 'extensions']) el(field).value = cfg[field];
|
||||
el('auto').checked = cfg.auto;
|
||||
const show = result => { el('status').textContent = result?.message || '尚无接管记录;可先检查桌面连接。'; };
|
||||
show((await chrome.storage.local.get('lastResult')).lastResult);
|
||||
chrome.storage.onChanged.addListener(changes => { if (changes.lastResult) show(changes.lastResult.newValue); });
|
||||
async function send(message, button) {
|
||||
button.disabled = true;
|
||||
try { show(await chrome.runtime.sendMessage(message)); } catch (error) { show({message: error.message}); }
|
||||
finally { button.disabled = false; }
|
||||
}
|
||||
el('ping').onclick = event => send({action: 'ping'}, event.target);
|
||||
el('send').onsubmit = event => { event.preventDefault(); send({action: 'send', url: el('url').value}, event.submitter); };
|
||||
el('settings').onsubmit = async event => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
if (el('auto').checked && !(await chrome.permissions.request({permissions: ['webRequest'], origins: ['http://*/*', 'https://*/*']}))) {
|
||||
el('auto').checked = false; return show({message: '未授权站点访问,自动接管保持关闭。'});
|
||||
}
|
||||
await chrome.storage.local.set({config: {auto: el('auto').checked, sites: el('sites').value.trim(), extensions: el('extensions').value.trim()}});
|
||||
show({message: '接管设置已保存。'});
|
||||
} catch (error) { show({message: error.message}); }
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform></ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals"><ProjectGuid>{F8C0CDE7-9F20-4D81-A472-73BA1F151505}</ProjectGuid><VcpkgEnabled>false</VcpkgEnabled></PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Label="Configuration"><ConfigurationType>Application</ConfigurationType><PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet></PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<PropertyGroup><OutDir>$(ProjectDir)..\..\client\bin\</OutDir><IntDir>$(ProjectDir)obj\$(Configuration)\</IntDir><TargetName>ttdownloader_native_host</TargetName><TargetName Condition="'$(Configuration)'=='Debug'">ttdownloader_native_host_d</TargetName></PropertyGroup>
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<LanguageStandard>stdcpp20</LanguageStandard><AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions><ExceptionHandling>Sync</ExceptionHandling>
|
||||
<PreprocessorDefinitions>NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary Condition="'$(Configuration)'=='Debug'">MultiThreadedDebug</RuntimeLibrary>
|
||||
<RuntimeLibrary Condition="'$(Configuration)'=='Release'">MultiThreaded</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link><SubSystem>Console</SubSystem><MinimumRequiredVersion>6.01</MinimumRequiredVersion></Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup><ClCompile Include="main.cpp" /><ClCompile Include="..\shared\protocol.cpp" /><ClCompile Include="..\shared\pipe.cpp" /></ItemGroup>
|
||||
<ItemGroup><ClInclude Include="..\shared\protocol.h" /><ClInclude Include="..\shared\pipe.h" /><ClInclude Include="..\shared\identity.h" /></ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1 @@
|
||||
{"private":true,"type":"module"}
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
"%~dp0..\client\bin\ttdownloader_native_host.exe" --register chrome
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
namespace browser_bridge {
|
||||
inline constexpr char kExtensionOrigin[]="chrome-extension://mlidghkaimgommidibnmcflafblbhcdb/";
|
||||
inline constexpr char kHostName[]="com.ttstd.ttdownloader";
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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_;
|
||||
};
|
||||
}
|
||||
@@ -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}};
|
||||
}
|
||||
}
|
||||
@@ -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="");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#include "../shared/protocol.h"
|
||||
#include "../shared/pipe.h"
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <chrono>
|
||||
using namespace browser_bridge;
|
||||
static void Check(bool ok,const char* text) { if (!ok) throw std::runtime_error(text); }
|
||||
int main() {
|
||||
try {
|
||||
Message fields; std::string error;
|
||||
Check(Parse(R"({"action":"add","request_id":"abc-1","method":"GET","url":"https://example.test/中文.zip","filename":"\ud83d\ude80.zip"})",fields,error) && Validate(fields,error),"parse UTF-8 and surrogate pair");
|
||||
Message restored; Check(Parse(Serialize(fields),restored,error) && fields==restored,"JSON roundtrip");
|
||||
for (const std::string& invalid : {R"({"x":"1","x":"2"})",R"({"x":1})",R"({"x":"\ud800"})",R"({"x":{}})",R"({"x":"a"} trailing)"}) Check(!Parse(invalid,restored,error),"reject malformed flat protocol");
|
||||
auto invalid=fields; invalid["user_agent"]="test\r\nInjected: yes"; Check(!Validate(invalid,error),"reject header injection");
|
||||
invalid=fields; invalid["method"]="POST"; Check(!Validate(invalid,error),"reject POST");
|
||||
std::stringstream framed; Check(WriteFrame(framed,Serialize(fields)),"write native frame");
|
||||
std::string json; Check(ReadFrame(framed,json) && json==Serialize(fields),"read native frame");
|
||||
std::stringstream truncated(std::string("\xff\xff\xff\x7f",4)); Check(!ReadFrame(truncated,json),"bound frame allocation");
|
||||
std::stringstream partial(std::string("\x05\0\0\0ab",6)); Check(!ReadFrame(partial,json),"reject truncated frame");
|
||||
PipeServer server; auto name=PipeName()+L".Test."+std::to_wstring(GetCurrentProcessId());
|
||||
server.Start([](const std::string& json,HANDLE) {
|
||||
Message message; std::string error;
|
||||
if (!Parse(json,message,error) || !Validate(message,error)) return Serialize(Reply("invalid_request",error));
|
||||
return Serialize(Reply(Get(message,"action")=="ping"?"ready":"accepted","已接收",Get(message,"request_id"),"42"));
|
||||
},name);
|
||||
Message ping{{"action","ping"},{"request_id","ping-1"}};
|
||||
bool ready=false;
|
||||
for (int i=0;i<50;++i) {
|
||||
auto response=Exchange(Serialize(ping),name);
|
||||
Check(Parse(response,restored,error),"pipe reply JSON");
|
||||
if (Get(restored,"status")=="ready") { ready=true; break; } Sleep(20);
|
||||
}
|
||||
Check(ready,"private per-user named pipe handshake");
|
||||
auto response=Exchange(Serialize(fields),name); Check(Parse(response,restored,error) && Get(restored,"status")=="accepted" && Get(restored,"task_id")=="42","native IPC request/ack including Unicode");
|
||||
// A stalled peer must not keep shutdown blocked in a read operation.
|
||||
HANDLE peer=INVALID_HANDLE_VALUE;
|
||||
for (int i=0;i<50 && peer==INVALID_HANDLE_VALUE;++i) {
|
||||
peer=CreateFileW(name.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,0,nullptr);
|
||||
if (peer==INVALID_HANDLE_VALUE) Sleep(20);
|
||||
}
|
||||
Check(peer!=INVALID_HANDLE_VALUE,"connect stalled peer");
|
||||
auto start=std::chrono::steady_clock::now(); server.Stop(); CloseHandle(peer);
|
||||
Check(std::chrono::steady_clock::now()-start<std::chrono::seconds(2),"stop cancels pending pipe I/O");
|
||||
std::cout<<"PASS: native framing, UTF-8, protocol bounds, request validation, named-pipe IPC and shutdown\n";
|
||||
return 0;
|
||||
} catch (const std::exception& error) { std::cerr<<"FAIL: "<<error.what()<<"\n"; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform></ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals"><ProjectGuid>{DD6207AB-5434-4613-9173-4DB0FD5DF97C}</ProjectGuid><VcpkgEnabled>false</VcpkgEnabled></PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Label="Configuration"><ConfigurationType>Application</ConfigurationType><PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet></PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<PropertyGroup><OutDir>$(ProjectDir)..\..\client\bin\tests\$(Configuration)\</OutDir><IntDir>$(ProjectDir)obj\$(Configuration)\</IntDir><TargetName>browser_bridge_tests</TargetName></PropertyGroup>
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<LanguageStandard>stdcpp20</LanguageStandard><AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions><ExceptionHandling>Sync</ExceptionHandling>
|
||||
<PreprocessorDefinitions>NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary Condition="'$(Configuration)'=='Debug'">MultiThreadedDebug</RuntimeLibrary>
|
||||
<RuntimeLibrary Condition="'$(Configuration)'=='Release'">MultiThreaded</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link><SubSystem>Console</SubSystem><MinimumRequiredVersion>6.01</MinimumRequiredVersion></Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup><ClCompile Include="bridge_tests.cpp" /><ClCompile Include="..\shared\protocol.cpp" /><ClCompile Include="..\shared\pipe.cpp" /></ItemGroup>
|
||||
<ItemGroup><ClInclude Include="..\shared\protocol.h" /><ClInclude Include="..\shared\pipe.h" /><ClInclude Include="..\shared\identity.h" /></ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1,121 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import crypto from 'node:crypto';
|
||||
import {DEFAULTS, eligible, httpUrl, linkReferrer, handoff, recover} from '../chrome/logic.mjs';
|
||||
const request = {action:'add', request_id:'test-1', method:'GET', url:'https://example.com/file.zip', referrer:'', filename:'file.zip', user_agent:'test'};
|
||||
function mock() {
|
||||
const item = {id:1, url:request.url, finalUrl:request.url, state:'in_progress', paused:false, danger:'safe'};
|
||||
const data = {}, events = [];
|
||||
const api = {storage:{local:{
|
||||
async get(key) { return key === null ? structuredClone(data) : {[key]: structuredClone(data[key])}; },
|
||||
async set(values) { Object.assign(data, structuredClone(values)); }, async remove(key) { delete data[key]; }
|
||||
}}, downloads:{
|
||||
async search() { return [structuredClone(item)]; },
|
||||
async pause() { events.push('pause'); item.paused=true; },
|
||||
async resume() { events.push('resume'); item.paused=false; },
|
||||
async cancel() { events.push('cancel'); item.state='interrupted'; item.paused=false; }
|
||||
}};
|
||||
return {api,item,data,events};
|
||||
}
|
||||
test('extension identity matches the native host allowlist', () => {
|
||||
const manifest = JSON.parse(fs.readFileSync(new URL('../chrome/manifest.json', import.meta.url)));
|
||||
const id = [...crypto.createHash('sha256').update(Buffer.from(manifest.key,'base64')).digest().subarray(0,16)].map(v=>String.fromCharCode(97+(v>>4),97+(v&15))).join('');
|
||||
assert.ok(fs.readFileSync(new URL('../shared/identity.h',import.meta.url),'utf8').includes(`chrome-extension://${id}/`));
|
||||
assert.equal(DEFAULTS.auto,false);
|
||||
});
|
||||
test('auto capture requires observed GET and honors site/type filters', () => {
|
||||
const {item} = mock(); const observed = {method:'GET',time:Date.now()};
|
||||
assert.equal(eligible(item,DEFAULTS,observed),false);
|
||||
const config={auto:true,sites:'example.com',extensions:'.zip'};
|
||||
assert.equal(eligible(item,config,observed),true);
|
||||
assert.equal(eligible(item,config,{...observed,method:'POST'}),false);
|
||||
assert.equal(eligible(item,config,null),false);
|
||||
assert.equal(eligible({...item,paused:true},config,observed),false);
|
||||
assert.equal(eligible({...item,danger:'url'},config,observed),false);
|
||||
assert.equal(eligible(item,{...config,sites:'other.example'},observed),false);
|
||||
assert.equal(eligible(item,{...config,extensions:'.mp4'},observed),false);
|
||||
assert.equal(httpUrl('blob:https://example.com/file'),'');
|
||||
assert.equal(httpUrl('https://user:password@example.com/file'),'');
|
||||
});
|
||||
test('cancel browser only after desktop persisted acknowledgement', async () => {
|
||||
const m=mock();
|
||||
const result=await handoff(m.api,m.item,request,async r=>{assert.equal(m.item.paused,true); assert.equal(m.data.pending_1.phase,'sending'); m.events.push('ack'); return {status:'accepted',request_id:r.request_id,task_id:'42'};});
|
||||
assert.equal(result.status,'accepted'); assert.deepEqual(m.events,['pause','ack','cancel']); assert.equal(m.data.pending_1,undefined);
|
||||
});
|
||||
test('offline desktop and duplicate restore the original browser download', async () => {
|
||||
for (const status of ['client_not_running','duplicate']) {
|
||||
const m=mock(); const result=await handoff(m.api,m.item,request,async()=>({status,message:status}));
|
||||
assert.equal(result.status,'fallback'); assert.deepEqual(m.events,['pause','resume']); assert.equal(m.item.paused,false);
|
||||
}
|
||||
});
|
||||
test('mismatched acknowledgement never cancels the browser', async () => {
|
||||
const m=mock(); await handoff(m.api,m.item,request,async()=>({status:'accepted',request_id:'wrong',task_id:'42'}));
|
||||
assert.deepEqual(m.events,['pause','resume']);
|
||||
});
|
||||
test('native disconnect restores browser', async () => {
|
||||
const m=mock(); await handoff(m.api,m.item,request,async()=>{throw new Error('host lost');});
|
||||
assert.deepEqual(m.events,['pause','resume']);
|
||||
});
|
||||
test('cancel failure is journaled and recovery retries without resubmitting', async () => {
|
||||
const m=mock(); const cancel=m.api.downloads.cancel; m.api.downloads.cancel=async()=>{throw new Error('busy');};
|
||||
assert.equal((await handoff(m.api,m.item,request,async r=>({status:'accepted',request_id:r.request_id,task_id:'42'}))).status,'recovery_pending');
|
||||
assert.equal(m.data.pending_1.phase,'cancel'); m.api.downloads.cancel=cancel;
|
||||
await recover(m.api,async()=>assert.fail('must not resubmit accepted task'),false);
|
||||
assert.equal(m.item.state,'interrupted'); assert.equal(m.data.pending_1,undefined);
|
||||
});
|
||||
test('resume failure survives worker restart and can be recovered', async () => {
|
||||
const m=mock(); const resume=m.api.downloads.resume; m.api.downloads.resume=async()=>{throw new Error('busy');};
|
||||
await handoff(m.api,m.item,request,async()=>{throw new Error('offline');}); assert.equal(m.data.pending_1.phase,'resume');
|
||||
m.api.downloads.resume=resume; await recover(m.api,async()=>assert.fail('must resume without native retry'),false);
|
||||
assert.equal(m.item.paused,false); assert.equal(m.data.pending_1,undefined);
|
||||
});
|
||||
test('worker restart retries the same request id; disabling auto restores browser', async () => {
|
||||
for (const auto of [true,false]) {
|
||||
const m=mock(); m.item.paused=true;
|
||||
m.data.pending_1={id:1,request,phase:'sending',created:Date.now(),original:request.url};
|
||||
await recover(m.api,async r=>{assert.equal(r.request_id,'test-1'); return {status:'accepted',request_id:r.request_id,task_id:'42'};},auto);
|
||||
assert.equal(m.item.state,auto?'interrupted':'in_progress'); assert.equal(m.item.paused,false);
|
||||
}
|
||||
});
|
||||
|
||||
test('background worker wires observed GET to native acknowledgement before cancel', async () => {
|
||||
const m=mock();
|
||||
m.data.config={auto:true,sites:'example.com',extensions:'.zip'};
|
||||
function event() { return {listeners:[], addListener(fn){this.listeners.push(fn);}, removeListener(fn){this.listeners=this.listeners.filter(x=>x!==fn);}, hasListener(fn){return this.listeners.includes(fn);}, async emit(...args){for(const fn of [...this.listeners]) await fn(...args);}}; }
|
||||
const old=globalThis.chrome;
|
||||
const api={...m.api, runtime:{id:'test-extension',getURL:()=> 'chrome-extension://test-extension/',onInstalled:event(),onStartup:event(),onMessage:event(),
|
||||
connectNative(name){assert.equal(name,'com.ttstd.ttdownloader'); const port={onMessage:event(),onDisconnect:event(),disconnect(){},postMessage(r){m.events.push('ack');queueMicrotask(()=>port.onMessage.emit({status:'accepted',request_id:r.request_id,task_id:'42',message:'accepted'}));}}; return port;}},
|
||||
contextMenus:{onClicked:event()},alarms:{onAlarm:event(),create(){}},permissions:{onAdded:event(),onRemoved:event(),async contains(){return true;}},
|
||||
webRequest:{onBeforeRequest:event()},action:{async setBadgeText(){},async setBadgeBackgroundColor(){},async setTitle(){}},notifications:{create(_,callback){callback();}}};
|
||||
api.storage.onChanged=event(); api.downloads.onCreated=event(); globalThis.chrome=api;
|
||||
try {
|
||||
await import('../chrome/background.js');
|
||||
await new Promise(resolve=>setTimeout(resolve,10));
|
||||
await api.webRequest.onBeforeRequest.emit({url:request.url,method:'GET'});
|
||||
await api.downloads.onCreated.emit(m.item);
|
||||
assert.deepEqual(m.events,['pause','ack','cancel']); assert.equal(m.data.lastResult.status,'accepted');
|
||||
} finally { globalThis.chrome=old; }
|
||||
});
|
||||
|
||||
test('zero task id is not an acknowledgement', async () => {
|
||||
const m=mock(); await handoff(m.api,m.item,request,async()=>({status:'accepted',request_id:request.request_id,task_id:'0'}));
|
||||
assert.deepEqual(m.events,['pause','resume']);
|
||||
});
|
||||
test('restart never pauses a sending task that the user resumed', async () => {
|
||||
const m=mock(); m.data.pending_1={id:1,request,phase:'sending',created:Date.now(),original:request.url};
|
||||
await recover(m.api,async()=>assert.fail('do not resend'),true);
|
||||
assert.equal(m.item.paused,false); assert.deepEqual(m.events,[]);
|
||||
});
|
||||
test('storage failure during fallback must not strand a paused download', async () => {
|
||||
const m=mock(); const set=m.api.storage.local.set;
|
||||
m.api.storage.local.set=async values=>{if(values.pending_1?.phase==='resume') throw new Error('quota'); return set(values);};
|
||||
await handoff(m.api,m.item,request,async()=>{throw new Error('offline');});
|
||||
assert.equal(m.item.paused,false);
|
||||
});
|
||||
|
||||
test('manual cross-site handoff does not leak source query parameters', () => {
|
||||
assert.equal(linkReferrer('https://source.test/page?secret=value','https://download.test/file'),'https://source.test/');
|
||||
assert.equal(linkReferrer('https://source.test/page?secret=value','http://download.test/file'),'');
|
||||
assert.equal(linkReferrer('https://source.test/page#fragment','https://source.test/file'),'https://source.test/page');
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import json, pathlib, re, struct, subprocess, sys
|
||||
root = pathlib.Path(__file__).resolve().parents[2]
|
||||
origin = re.search(r'kExtensionOrigin\[\]="([^"]+)"', (root/'browser/shared/identity.h').read_text()).group(1)
|
||||
def frame(value):
|
||||
raw=json.dumps(value,ensure_ascii=False).encode('utf-8')
|
||||
return struct.pack('<I',len(raw))+raw
|
||||
# Invalid requests never reach the real desktop or touch user tasks.
|
||||
requests=[{'action':'add','request_id':'bad-1','method':'POST','url':'https://example.test/file'}, {'action':'add','request_id':'bad-2','method':'GET','url':'file:///C:/secret'}, {'action':'ping','request_id':123}]
|
||||
result=subprocess.run([sys.argv[1],origin],input=b''.join(map(frame,requests)),capture_output=True,timeout=10)
|
||||
assert result.returncode==0, result.stderr
|
||||
raw=result.stdout
|
||||
for request in requests:
|
||||
assert len(raw)>=4
|
||||
length=struct.unpack('<I',raw[:4])[0]
|
||||
response=json.loads(raw[4:4+length]); raw=raw[4+length:]
|
||||
assert response['status']=='invalid_request',response
|
||||
assert raw==b'', 'stdout must contain only framed JSON'
|
||||
wrong=subprocess.run([sys.argv[1],'chrome-extension://wrong/'],input=frame({'action':'ping','request_id':'test'}),capture_output=True,timeout=5)
|
||||
assert wrong.returncode!=0 and not wrong.stdout
|
||||
print('PASS: compiled Native Messaging Host framing and extension-origin validation')
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
"%~dp0..\client\bin\ttdownloader_native_host.exe" --unregister chrome
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "stdafx.h"
|
||||
#include "client_browser_bridge.h"
|
||||
#include "download_engine.h"
|
||||
#include "platform.h"
|
||||
#include "../../browser/shared/protocol.h"
|
||||
#include <chrono>
|
||||
std::unique_ptr<browser_bridge::PipeServer> StartBrowserBridge(DownloadEngine& engine) {
|
||||
auto server=std::make_unique<browser_bridge::PipeServer>();
|
||||
server->Start([&engine](const std::string& json,HANDLE stop) {
|
||||
using namespace browser_bridge;
|
||||
Message fields; std::string error;
|
||||
if (!Parse(json,fields,error) || !Validate(fields,error)) return Serialize(Reply("invalid_request",error));
|
||||
auto id=Get(fields,"request_id");
|
||||
if (!engine.Ready()) return Serialize(Reply("client_not_ready","下载引擎尚未就绪",id));
|
||||
if (Get(fields,"action")=="ping") return Serialize(Reply("ready","桌面客户端已连接",id));
|
||||
ExternalDownload request{platform::FromUtf8(id),platform::FromUtf8(Get(fields,"url")),platform::FromUtf8(Get(fields,"referrer")),
|
||||
platform::FromUtf8(Get(fields,"user_agent")),platform::FromUtf8(Get(fields,"filename"))};
|
||||
auto pending=engine.SubmitExternal(std::move(request));
|
||||
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(20);
|
||||
std::unique_lock lock(pending->mutex);
|
||||
while (!pending->done) {
|
||||
if (WaitForSingleObject(stop,0)==WAIT_OBJECT_0 || std::chrono::steady_clock::now()>=deadline) {
|
||||
pending->canceled=true;
|
||||
return Serialize(Reply("busy","任务引擎繁忙,未确认接管,请继续使用浏览器下载",id));
|
||||
}
|
||||
pending->changed.wait_for(lock,std::chrono::milliseconds(50));
|
||||
}
|
||||
return Serialize(Reply(pending->status,pending->message,id,std::to_string(pending->task_id)));
|
||||
});
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
#include "../../browser/shared/pipe.h"
|
||||
#include <memory>
|
||||
class DownloadEngine;
|
||||
std::unique_ptr<browser_bridge::PipeServer> StartBrowserBridge(DownloadEngine&);
|
||||
@@ -23,6 +23,10 @@ namespace
|
||||
|
||||
std::wstring GetDefaultSaveDir()
|
||||
{
|
||||
PWSTR known=nullptr;
|
||||
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Downloads,KF_FLAG_DONT_VERIFY,nullptr,&known))) {
|
||||
std::wstring directory(known); CoTaskMemFree(known); return directory;
|
||||
}
|
||||
wchar_t profile[MAX_PATH] = { 0 };
|
||||
if (::GetEnvironmentVariableW(L"USERPROFILE", profile, MAX_PATH) == 0)
|
||||
return L".";
|
||||
@@ -118,6 +122,12 @@ namespace
|
||||
if (name.empty())
|
||||
name = L"download";
|
||||
|
||||
auto stem=name.substr(0,name.find(L'.'));
|
||||
bool reserved=_wcsicmp(stem.c_str(),L"CON")==0 || _wcsicmp(stem.c_str(),L"PRN")==0 || _wcsicmp(stem.c_str(),L"AUX")==0 || _wcsicmp(stem.c_str(),L"NUL")==0;
|
||||
if (stem.size()==4 && stem[3]>=L'1' && stem[3]<=L'9')
|
||||
reserved=reserved || _wcsnicmp(stem.c_str(),L"COM",3)==0 || _wcsnicmp(stem.c_str(),L"LPT",3)==0;
|
||||
if (reserved) name=L"_"+name;
|
||||
|
||||
if (name.size() > 120)
|
||||
{
|
||||
size_t dot = name.find_last_of(L'.');
|
||||
@@ -236,6 +246,7 @@ void DownloadEngine::Start()
|
||||
|
||||
void DownloadEngine::Stop()
|
||||
{
|
||||
ready_=false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
||||
stop_ = true;
|
||||
@@ -258,6 +269,13 @@ void DownloadEngine::AddTask(const std::wstring& url, const std::wstring& save_d
|
||||
cmd_cv_.notify_all();
|
||||
}
|
||||
|
||||
std::shared_ptr<ExternalSubmission> DownloadEngine::SubmitExternal(ExternalDownload request) {
|
||||
Command cmd; cmd.kind=Command::kAdd; cmd.url=request.url; cmd.external=std::move(request);
|
||||
auto state=std::make_shared<ExternalSubmission>(); cmd.submission=state;
|
||||
{ std::lock_guard lock(cmd_mutex_); commands_.push_back(std::move(cmd)); }
|
||||
cmd_cv_.notify_all(); return state;
|
||||
}
|
||||
|
||||
void DownloadEngine::PauseTask(int64_t id)
|
||||
{
|
||||
Command cmd;
|
||||
@@ -351,6 +369,7 @@ void DownloadEngine::ThreadMain()
|
||||
PostEvent(event);
|
||||
}
|
||||
|
||||
ready_=store_open_;
|
||||
while (!stop_)
|
||||
{
|
||||
DrainCommands();
|
||||
@@ -390,6 +409,7 @@ void DownloadEngine::ThreadMain()
|
||||
[this]() { return stop_.load() || !commands_.empty(); });
|
||||
}
|
||||
|
||||
ready_=false;
|
||||
store_.Close();
|
||||
}
|
||||
|
||||
@@ -423,25 +443,41 @@ void DownloadEngine::DrainCommands()
|
||||
|
||||
void DownloadEngine::HandleAdd(const Command& cmd)
|
||||
{
|
||||
std::unique_lock<std::mutex> decision;
|
||||
if (cmd.submission) {
|
||||
decision=std::unique_lock<std::mutex>(cmd.submission->mutex);
|
||||
if (cmd.submission->canceled) return;
|
||||
}
|
||||
auto reply=[&](const std::string& status,const std::wstring& message,int64_t id=0) {
|
||||
if (!cmd.submission) return;
|
||||
cmd.submission->status=status; cmd.submission->message=platform::ToUtf8(message);
|
||||
cmd.submission->task_id=id; cmd.submission->done=true; cmd.submission->changed.notify_all();
|
||||
};
|
||||
auto reject=[&](const std::wstring& message) { reply("rejected",message); PostRejected(message,cmd.external.request_id); };
|
||||
std::wstring url = Trim(cmd.url);
|
||||
if (url.empty())
|
||||
{
|
||||
PostRejected(L"下载链接不能为空");
|
||||
reject(L"下载链接不能为空");
|
||||
return;
|
||||
}
|
||||
|
||||
http::UrlParts parts;
|
||||
if (!transport_->ParseUrl(url, parts))
|
||||
{
|
||||
PostRejected(L"仅支持有效的 HTTP/HTTPS 链接");
|
||||
reject(L"仅支持有效的 HTTP/HTTPS 链接");
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& entry : tasks_)
|
||||
{
|
||||
if (!cmd.external.request_id.empty() && entry.second.request_id==cmd.external.request_id && entry.second.url!=url) {
|
||||
reject(L"请求编号已用于其他下载地址"); return;
|
||||
}
|
||||
if (entry.second.url == url)
|
||||
{
|
||||
PostRejected(L"链接已存在");
|
||||
if (!cmd.external.request_id.empty() && entry.second.request_id==cmd.external.request_id)
|
||||
reply("accepted",L"此请求已接管",entry.first);
|
||||
else { reply("duplicate",L"链接已存在",entry.first); PostRejected(L"链接已存在",cmd.external.request_id); }
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -453,19 +489,24 @@ void DownloadEngine::HandleAdd(const Command& cmd)
|
||||
dir.pop_back();
|
||||
if (!EnsureDirectory(dir))
|
||||
{
|
||||
PostRejected(L"保存目录不可用");
|
||||
reject(L"保存目录不可用");
|
||||
return;
|
||||
}
|
||||
|
||||
TaskInfo task;
|
||||
task.url = url;
|
||||
task.file_name = FileNameFromUrl(url,*transport_);
|
||||
task.file_name = FileNameFromUrl(url,*transport_);
|
||||
if (!cmd.external.filename.empty()) {
|
||||
auto slash=cmd.external.filename.find_last_of(L"/\\");
|
||||
task.file_name=SanitizeFileName(cmd.external.filename.substr(slash==std::wstring::npos?0:slash+1));
|
||||
}
|
||||
task.request_id=cmd.external.request_id; task.referrer=cmd.external.referrer; task.user_agent=cmd.external.user_agent;
|
||||
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
||||
task.state = TaskState::kQueued;
|
||||
|
||||
if (!store_open_ || !store_.Insert(task))
|
||||
{
|
||||
PostRejected(L"无法写入任务数据库");
|
||||
reject(L"无法写入任务数据库");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -475,7 +516,9 @@ void DownloadEngine::HandleAdd(const Command& cmd)
|
||||
EngineEvent* event = new EngineEvent;
|
||||
event->type = EngineEventType::kTaskAdded;
|
||||
event->task = task;
|
||||
event->request_id=cmd.external.request_id;
|
||||
PostEvent(event);
|
||||
reply("accepted",L"任务已保存并交给 TTDownloader",task.id);
|
||||
}
|
||||
|
||||
void DownloadEngine::HandlePause(int64_t id)
|
||||
@@ -644,6 +687,7 @@ DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
||||
http::Request request;
|
||||
request.url=task.url;
|
||||
request.range_offset=offset;
|
||||
request.referrer=task.referrer; request.user_agent=task.user_agent;
|
||||
auto opened=transport_->Open(request);
|
||||
if (!opened.stream) {
|
||||
error=opened.error;
|
||||
@@ -813,10 +857,11 @@ void DownloadEngine::PostUpdate(const TaskInfo& task, double speed)
|
||||
PostEvent(event);
|
||||
}
|
||||
|
||||
void DownloadEngine::PostRejected(const std::wstring& message)
|
||||
void DownloadEngine::PostRejected(const std::wstring& message,const std::wstring& request_id)
|
||||
{
|
||||
EngineEvent* event = new EngineEvent;
|
||||
event->type = EngineEventType::kTaskRejected;
|
||||
event->message = message;
|
||||
event->request_id=request_id;
|
||||
PostEvent(event);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "task_store.h"
|
||||
#include "http_transport.h"
|
||||
#include "external_download.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
@@ -31,6 +32,7 @@ struct EngineEvent
|
||||
std::vector<TaskInfo> tasks;
|
||||
std::wstring message;
|
||||
double speed = 0.0;
|
||||
std::wstring request_id;
|
||||
};
|
||||
|
||||
class DownloadEngine
|
||||
@@ -40,6 +42,8 @@ public:
|
||||
DownloadEngine(HWND notify_wnd,std::unique_ptr<http::Transport> transport);
|
||||
~DownloadEngine();
|
||||
|
||||
bool Ready() const { return ready_.load(); }
|
||||
std::shared_ptr<ExternalSubmission> SubmitExternal(ExternalDownload request);
|
||||
void Start();
|
||||
void Stop();
|
||||
|
||||
@@ -65,6 +69,8 @@ private:
|
||||
bool delete_file = false;
|
||||
std::wstring url;
|
||||
std::wstring save_dir;
|
||||
ExternalDownload external;
|
||||
std::shared_ptr<ExternalSubmission> submission;
|
||||
};
|
||||
|
||||
enum class AttemptResult
|
||||
@@ -88,12 +94,13 @@ private:
|
||||
|
||||
void PostEvent(EngineEvent* event);
|
||||
void PostUpdate(const TaskInfo& task, double speed);
|
||||
void PostRejected(const std::wstring& message);
|
||||
void PostRejected(const std::wstring& message,const std::wstring& request_id=L"");
|
||||
|
||||
HWND notify_wnd_ = nullptr;
|
||||
std::unique_ptr<http::Transport> transport_;
|
||||
std::thread thread_;
|
||||
std::atomic<bool> stop_{ false };
|
||||
std::atomic<bool> ready_{false};
|
||||
|
||||
std::mutex cmd_mutex_;
|
||||
std::condition_variable cmd_cv_;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "file_drop_source.h"
|
||||
#include "settings_form.h"
|
||||
#include "add_task_form.h"
|
||||
#include "client_browser_bridge.h"
|
||||
|
||||
#include <windowsx.h>
|
||||
#include <commctrl.h>
|
||||
@@ -158,6 +159,7 @@ void DownloaderForm::OnCreate() {
|
||||
DrawMenuBar(GetHWND());
|
||||
ApplySkinSettings(); UpdateSummary(); AddTrayIcon();
|
||||
engine_=std::make_unique<DownloadEngine>(GetHWND()); engine_->Start();
|
||||
browser_bridge_=StartBrowserBridge(*engine_);
|
||||
}
|
||||
void DownloaderForm::OnLayout() {
|
||||
float w=Width(),h=Height();
|
||||
@@ -276,6 +278,7 @@ std::optional<LRESULT> DownloaderForm::OnMessage(UINT msg,WPARAM wp,LPARAM lp) {
|
||||
return {};
|
||||
}
|
||||
void DownloaderForm::StopEngine() {
|
||||
browser_bridge_.reset();
|
||||
if (engine_) { engine_->Stop(); engine_.reset(); }
|
||||
MSG message{};
|
||||
while (GetHWND() && PeekMessageW(&message,GetHWND(),DownloadEngine::kEventMessage,DownloadEngine::kEventMessage,PM_REMOVE))
|
||||
@@ -312,7 +315,7 @@ void DownloaderForm::HandleEngineEvent(const EngineEvent& event) {
|
||||
UpdateViewport(); UpdateSummary(); break;
|
||||
case EngineEventType::kTaskAdded:
|
||||
if (index<0) { indices_[event.task.id]=static_cast<int>(rows_.size()); rows_.push_back({event.task,event.speed}); }
|
||||
if (add_task_form_ && add_task_form_->Pending() && add_task_form_->SubmittedUrl()==event.task.url) add_task_form_->Complete(true);
|
||||
if (event.request_id.empty() && add_task_form_ && add_task_form_->Pending() && add_task_form_->SubmittedUrl()==event.task.url) add_task_form_->Complete(true);
|
||||
UpdateViewport(); UpdateSummary(); break;
|
||||
case EngineEventType::kTaskUpdated:
|
||||
if (index>=0) rows_[index]={event.task,event.speed}; break;
|
||||
@@ -325,7 +328,7 @@ void DownloaderForm::HandleEngineEvent(const EngineEvent& event) {
|
||||
}
|
||||
UpdateViewport(); UpdateSummary(); break;
|
||||
case EngineEventType::kTaskRejected:
|
||||
if (add_task_form_) add_task_form_->Complete(false,event.message);
|
||||
if (event.request_id.empty() && add_task_form_) add_task_form_->Complete(false,event.message);
|
||||
UpdateSummary(event.message); break;
|
||||
case EngineEventType::kFatal:
|
||||
engine_failed_=true;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <unordered_map>
|
||||
class SettingsForm;
|
||||
class AddTaskForm;
|
||||
namespace browser_bridge { class PipeServer; }
|
||||
class DownloaderForm final : public ttui::Window {
|
||||
public:
|
||||
DownloaderForm();
|
||||
@@ -56,6 +57,7 @@ private:
|
||||
std::vector<TaskRow> rows_;
|
||||
std::unordered_map<int64_t,int> indices_;
|
||||
std::unique_ptr<DownloadEngine> engine_;
|
||||
std::unique_ptr<browser_bridge::PipeServer> browser_bridge_;
|
||||
bool engine_failed_=false;
|
||||
bool drag_pending_=false;
|
||||
POINT drag_origin_{};
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
struct ExternalDownload {
|
||||
std::wstring request_id,url,referrer,user_agent,filename;
|
||||
};
|
||||
struct ExternalSubmission {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool done=false,canceled=false;
|
||||
std::string status,message;
|
||||
int64_t task_id=0;
|
||||
};
|
||||
@@ -22,6 +22,7 @@ struct Request {
|
||||
std::wstring url;
|
||||
std::int64_t range_offset=0;
|
||||
Timeouts timeouts;
|
||||
std::wstring referrer,user_agent;
|
||||
};
|
||||
struct Response {
|
||||
unsigned status=0;
|
||||
|
||||
@@ -61,6 +61,9 @@ bool TaskStore::Open(const std::wstring& db_path)
|
||||
ExecIgnoringError(db_, "ALTER TABLE tasks ADD COLUMN total_bytes INTEGER NOT NULL DEFAULT 0;");
|
||||
ExecIgnoringError(db_, "ALTER TABLE tasks ADD COLUMN downloaded_bytes INTEGER NOT NULL DEFAULT 0;");
|
||||
ExecIgnoringError(db_, "ALTER TABLE tasks ADD COLUMN error TEXT NOT NULL DEFAULT '';");
|
||||
ExecIgnoringError(db_, "ALTER TABLE tasks ADD COLUMN request_id TEXT NOT NULL DEFAULT ''; ");
|
||||
ExecIgnoringError(db_, "ALTER TABLE tasks ADD COLUMN referrer TEXT NOT NULL DEFAULT ''; ");
|
||||
ExecIgnoringError(db_, "ALTER TABLE tasks ADD COLUMN user_agent TEXT NOT NULL DEFAULT ''; ");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -79,7 +82,7 @@ std::vector<TaskInfo> TaskStore::LoadTasks()
|
||||
|
||||
sqlite3_stmt* stmt = nullptr;
|
||||
if (sqlite3_prepare_v2(db_,
|
||||
"SELECT id, url, save_path, file_name, state, total_bytes, downloaded_bytes, error "
|
||||
"SELECT id, url, save_path, file_name, state, total_bytes, downloaded_bytes, error, request_id, referrer, user_agent "
|
||||
"FROM tasks ORDER BY id;", -1, &stmt, nullptr) != SQLITE_OK)
|
||||
return tasks;
|
||||
|
||||
@@ -94,6 +97,7 @@ std::vector<TaskInfo> TaskStore::LoadTasks()
|
||||
task.total_bytes = sqlite3_column_int64(stmt, 5);
|
||||
task.downloaded_bytes = sqlite3_column_int64(stmt, 6);
|
||||
task.error = ColumnText(stmt, 7);
|
||||
task.request_id=ColumnText(stmt,8); task.referrer=ColumnText(stmt,9); task.user_agent=ColumnText(stmt,10);
|
||||
tasks.push_back(task);
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
@@ -104,8 +108,8 @@ bool TaskStore::Insert(TaskInfo& task)
|
||||
{
|
||||
sqlite3_stmt* stmt = nullptr;
|
||||
if (sqlite3_prepare_v2(db_,
|
||||
"INSERT INTO tasks(url, save_path, file_name, state, total_bytes, downloaded_bytes) "
|
||||
"VALUES(?, ?, ?, ?, ?, ?);", -1, &stmt, nullptr) != SQLITE_OK)
|
||||
"INSERT INTO tasks(url, save_path, file_name, state, total_bytes, downloaded_bytes, request_id, referrer, user_agent) "
|
||||
"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);", -1, &stmt, nullptr) != SQLITE_OK)
|
||||
return false;
|
||||
|
||||
BindText(stmt, 1, task.url);
|
||||
@@ -114,6 +118,7 @@ bool TaskStore::Insert(TaskInfo& task)
|
||||
sqlite3_bind_int(stmt, 4, static_cast<int>(task.state));
|
||||
sqlite3_bind_int64(stmt, 5, task.total_bytes);
|
||||
sqlite3_bind_int64(stmt, 6, task.downloaded_bytes);
|
||||
BindText(stmt,7,task.request_id); BindText(stmt,8,task.referrer); BindText(stmt,9,task.user_agent);
|
||||
|
||||
bool ok = sqlite3_step(stmt) == SQLITE_DONE;
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
@@ -25,6 +25,7 @@ struct TaskInfo
|
||||
int64_t total_bytes = 0;
|
||||
int64_t downloaded_bytes = 0;
|
||||
std::wstring error;
|
||||
std::wstring request_id,referrer,user_agent;
|
||||
};
|
||||
|
||||
class TaskStore
|
||||
|
||||
@@ -126,13 +126,17 @@ public:
|
||||
OpenResult Open(const Request& input) override {
|
||||
UrlParts parts;
|
||||
if (input.range_offset<0 || !ParseUrl(input.url,parts)) return {nullptr,OpenError::kInvalidRequest,L"无效的下载链接或续传偏移"};
|
||||
for (const auto* header : { &input.referrer,&input.user_agent }) {
|
||||
if (header->size()>16384) return {nullptr,OpenError::kInvalidRequest,L"请求上下文过长"};
|
||||
for (wchar_t c:*header) if (c<32 || c==127) return {nullptr,OpenError::kInvalidRequest,L"请求上下文含无效字符"};
|
||||
}
|
||||
const auto& timeout=input.timeouts;
|
||||
if (timeout.resolve_ms<=0 || timeout.connect_ms<=0 || timeout.send_ms<=0 || timeout.receive_ms<=0)
|
||||
return {nullptr,OpenError::kInvalidRequest,L"网络超时必须大于零"};
|
||||
Handle session(WinHttpOpen(L"TTDownloader/0.1",WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
||||
Handle session(WinHttpOpen(input.user_agent.empty()?L"TTDownloader/0.1":input.user_agent.c_str(),WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
||||
WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0),&::WinHttpCloseHandle);
|
||||
const bool legacy_proxy=!session && GetLastError()==ERROR_INVALID_PARAMETER;
|
||||
if (legacy_proxy) session.reset(WinHttpOpen(L"TTDownloader/0.1",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
|
||||
if (legacy_proxy) session.reset(WinHttpOpen(input.user_agent.empty()?L"TTDownloader/0.1":input.user_agent.c_str(),WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
|
||||
WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0));
|
||||
if (!session) return Failure(L"无法初始化网络连接:",GetLastError());
|
||||
if (legacy_proxy) {
|
||||
@@ -143,7 +147,7 @@ public:
|
||||
return Failure(L"无法设置网络超时:",GetLastError());
|
||||
Handle connection(WinHttpConnect(session.get(),parts.host.c_str(),parts.port,0),&::WinHttpCloseHandle);
|
||||
if (!connection) return Failure(L"无法连接服务器:",GetLastError());
|
||||
Handle request(WinHttpOpenRequest(connection.get(),L"GET",parts.path.c_str(),nullptr,WINHTTP_NO_REFERER,
|
||||
Handle request(WinHttpOpenRequest(connection.get(),L"GET",parts.path.c_str(),nullptr,input.referrer.empty()?WINHTTP_NO_REFERER:input.referrer.c_str(),
|
||||
WINHTTP_DEFAULT_ACCEPT_TYPES,parts.https?WINHTTP_FLAG_SECURE:0),&::WinHttpCloseHandle);
|
||||
if (!request) return Failure(L"无法创建下载请求:",GetLastError());
|
||||
if (!WinHttpSetTimeouts(request.get(),timeout.resolve_ms,timeout.connect_ms,timeout.send_ms,timeout.receive_ms))
|
||||
|
||||
@@ -77,6 +77,12 @@ static void Run(const std::wstring& base) {
|
||||
Check(response.stream->Read({}).state==http::ReadState::kError,"empty read buffer is not mistaken for EOF");
|
||||
Check(Drain(*response.stream)==payload,"invalid read does not consume data");
|
||||
}
|
||||
{
|
||||
http::Request context; context.url=base+L"/context"; context.referrer=L"https://example.test/source"; context.user_agent=L"TTDownloader Browser Bridge Test";
|
||||
auto response=transport->Open(context); Check(response.stream && response.stream->Headers().status==200 && Drain(*response.stream)==payload,"browser referrer and user agent forwarded");
|
||||
context.user_agent=L"bad\r\nInjected: yes";
|
||||
Check(transport->Open(context).kind==http::OpenError::kInvalidRequest,"browser headers cannot inject additional headers");
|
||||
}
|
||||
http::Request invalid; invalid.url=L"ftp://example.test/file";
|
||||
Check(transport->Open(invalid).kind==http::OpenError::kInvalidRequest,"invalid URL classification");
|
||||
invalid.url=base+L"/plain"; invalid.range_offset=-1;
|
||||
|
||||
@@ -52,7 +52,10 @@ class Handler(http.server.BaseHTTPRequestHandler):
|
||||
body = PAYLOAD
|
||||
code = 200
|
||||
content_range = None
|
||||
if path == "/range":
|
||||
if path == "/context":
|
||||
if self.headers.get("Referer") != "https://example.test/source" or self.headers.get("User-Agent") != "TTDownloader Browser Bridge Test":
|
||||
code, body = 400, b"missing browser context"
|
||||
elif path == "/range":
|
||||
if self.headers.get("Range") != "bytes=123-":
|
||||
code, body = 400, b"wrong range"
|
||||
else:
|
||||
|
||||
@@ -100,6 +100,8 @@
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="src\add_task_form.h" />
|
||||
<ClInclude Include="src\client_browser_bridge.h" />
|
||||
<ClInclude Include="src\external_download.h" />
|
||||
<ClInclude Include="src\download_engine.h" />
|
||||
<ClInclude Include="src\http_transport.h" />
|
||||
<ClInclude Include="src\winhttp_transport.h" />
|
||||
@@ -113,6 +115,9 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="src\add_task_form.cpp" />
|
||||
<ClCompile Include="src\client_browser_bridge.cpp" />
|
||||
<ClCompile Include="..\browser\shared\protocol.cpp"><PrecompiledHeader>NotUsing</PrecompiledHeader></ClCompile>
|
||||
<ClCompile Include="..\browser\shared\pipe.cpp"><PrecompiledHeader>NotUsing</PrecompiledHeader></ClCompile>
|
||||
<ClCompile Include="src\download_engine.cpp" />
|
||||
<ClCompile Include="src\http_transport.cpp" />
|
||||
<ClCompile Include="src\winhttp_transport.cpp" />
|
||||
|
||||
@@ -11,6 +11,12 @@ if not defined TTUI_MSBUILD (
|
||||
if errorlevel 1 exit /b 1
|
||||
"%TTUI_MSBUILD%" "%~dp0client\tests\http_transport_tests.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal
|
||||
if errorlevel 1 exit /b 1
|
||||
"%TTUI_MSBUILD%" "%~dp0browser\native\native_host.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal
|
||||
if errorlevel 1 exit /b 1
|
||||
"%TTUI_MSBUILD%" "%~dp0browser\tests\browser_bridge_tests.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal
|
||||
if errorlevel 1 exit /b 1
|
||||
set "BROWSER_HOST_EXE=ttdownloader_native_host.exe"
|
||||
if /i "%TTUI_TEST_CONFIG%"=="Debug" set "BROWSER_HOST_EXE=ttdownloader_native_host_d.exe"
|
||||
pushd "%~dp0"
|
||||
"%~dp0ui\ttui\lib\x64\%TTUI_TEST_CONFIG%\smoke.exe"
|
||||
if errorlevel 1 (
|
||||
@@ -18,6 +24,21 @@ if errorlevel 1 (
|
||||
exit /b 1
|
||||
)
|
||||
python "%~dp0client\tests\run_http_transport_tests.py" "%~dp0client\bin\tests\%TTUI_TEST_CONFIG%\http_transport_tests.exe"
|
||||
if errorlevel 1 (
|
||||
popd
|
||||
exit /b 1
|
||||
)
|
||||
"%~dp0client\bin\tests\%TTUI_TEST_CONFIG%\browser_bridge_tests.exe"
|
||||
if errorlevel 1 (
|
||||
popd
|
||||
exit /b 1
|
||||
)
|
||||
node --test "%~dp0browser\tests\extension.test.mjs"
|
||||
if errorlevel 1 (
|
||||
popd
|
||||
exit /b 1
|
||||
)
|
||||
python "%~dp0browser\tests\host_stdio_test.py" "%~dp0client\bin\%BROWSER_HOST_EXE%"
|
||||
set "TTUI_TEST_EXIT=%ERRORLEVEL%"
|
||||
popd
|
||||
endlocal & exit /b %TTUI_TEST_EXIT%
|
||||
@@ -65,6 +65,7 @@ int main() {
|
||||
auto path=folder/(L"test_tasks_"+std::to_wstring(GetCurrentProcessId())+L".db");
|
||||
TaskStore store; Check(store.Open(path.wstring()),"open isolated SQLite store");
|
||||
TaskInfo task; task.url=L"https://example.test/中文🚀.bin";
|
||||
task.request_id=L"browser-test-1"; task.referrer=L"https://example.test/页面"; task.user_agent=L"Browser test agent";
|
||||
task.file_name=L"中文🚀.bin"; task.save_path=L"D:\\下载\\中文🚀.bin";
|
||||
Check(store.Insert(task) && task.id>0,"insert task with Unicode");
|
||||
Check(store.UpdateProgress(task.id,123,456),"persist progress");
|
||||
@@ -73,7 +74,8 @@ int main() {
|
||||
auto restored=store.LoadTasks();
|
||||
Check(restored.size()==1 && restored[0].url==task.url && restored[0].save_path==task.save_path
|
||||
&& restored[0].file_name==task.file_name && restored[0].state==TaskState::kPaused
|
||||
&& restored[0].downloaded_bytes==123 && restored[0].error==L"暂停测试","task recovery and UTF-8 persistence");
|
||||
&& restored[0].downloaded_bytes==123 && restored[0].error==L"暂停测试"
|
||||
&& restored[0].request_id==task.request_id && restored[0].referrer==task.referrer && restored[0].user_agent==task.user_agent,"task recovery and UTF-8 persistence");
|
||||
Check(store.DeleteTask(task.id) && store.LoadTasks().empty(),"remove isolated task");
|
||||
store.Close();
|
||||
std::filesystem::remove(path);
|
||||
|
||||
Reference in new issue
Block a user