From eb3df9aa3df8b59324e3dfe0b2463408d9e91cdb Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Fri, 27 Nov 2026 11:28:30 +0800 Subject: [PATCH] Add FTP and magnet backends, tracker and proxy settings, and organize client modules Integrate pinned libcurl, libtorrent and static OpenSSL dependencies with license notices. Enable verified HTTPS trackers and authenticated HTTP/SOCKS5 proxies, add tracker TXT import without arbitrary list caps, and allow resizing the main window. Organize client sources by responsibility and update Visual Studio projects, filters and tests. Debug and Release builds passed, along with UI, HTTP, tracker import and browser bridge regressions. Full protocol tests have an unresolved intermittent HTTPS tracker wait timeout; Windows 7 runtime validation remains outstanding. --- .gitignore | 14 + AGENTS.md | 39 +- browser/README.md | 18 + browser/tests/bridge_tests.cpp | 2 +- browser/tests/browser_bridge_tests.vcxproj | 2 +- build.cmd | 3 + client/README.md | 16 + client/src/{ => app}/startup_options.h | 7 +- client/src/{ => engine}/download_engine.cpp | 87 +++- client/src/{ => engine}/download_engine.h | 14 +- client/src/engine/download_link.h | 12 + client/src/engine/torrent_backend.cpp | 142 ++++++ client/src/engine/torrent_backend.h | 18 + client/src/http_transport.cpp | 6 - .../client_browser_bridge.cpp | 8 +- .../{ => integration}/client_browser_bridge.h | 4 +- .../src/{ => integration}/external_download.h | 0 .../{ => integration}/file_drop_source.cpp | 2 +- .../src/{ => integration}/file_drop_source.h | 0 client/src/main.cpp | 6 +- client/src/{ => platform}/platform.h | 0 client/src/settings/proxy_settings.h | 61 +++ client/src/{ => settings}/skin_settings.h | 0 client/src/settings/tracker_import.cpp | 85 ++++ client/src/settings/tracker_import.h | 7 + client/src/settings/tracker_settings.h | 59 +++ client/src/{ => storage}/task_store.cpp | 4 +- client/src/{ => storage}/task_store.h | 0 client/src/transport/ftp_transport.cpp | 177 ++++++++ client/src/transport/ftp_transport.h | 3 + client/src/transport/http_transport.cpp | 17 + client/src/{ => transport}/http_transport.h | 0 .../src/{ => transport}/winhttp_transport.cpp | 4 +- .../src/{ => transport}/winhttp_transport.h | 2 +- client/src/{ => ui}/add_task_form.cpp | 4 +- client/src/{ => ui}/add_task_form.h | 2 +- client/src/{ => ui}/downloader_form.cpp | 55 ++- client/src/{ => ui}/downloader_form.h | 14 +- client/src/ui/proxy_form.cpp | 33 ++ client/src/ui/proxy_form.h | 20 + client/src/{ => ui}/settings_form.cpp | 2 +- client/src/{ => ui}/settings_form.h | 2 +- client/src/ui/tracker_form.cpp | 74 +++ client/src/ui/tracker_form.h | 26 ++ client/tests/http_transport_tests.cpp | 8 +- client/tests/http_transport_tests.vcxproj | 6 +- client/tests/protocol_tests.cpp | 185 ++++++++ client/tests/protocol_tests.vcxproj | 31 ++ client/tests/proxy_fixture.py | 69 +++ client/tests/run_protocol_tests.py | 79 ++++ client/ttdownloader.vcxproj | 58 ++- client/ttdownloader.vcxproj.filters | 160 +++++++ test.cmd | 9 + third_party/CMakeLists.txt | 40 ++ third_party/NOTICES.txt | 422 ++++++++++++++++++ third_party/README.md | 25 ++ third_party/build-openssl.ps1 | 33 ++ third_party/dependencies.props | 12 + third_party/prepare.ps1 | 37 ++ ui/ttui/include/ttui/window.h | 2 +- ui/ttui/src/window.cpp | 6 +- ui/ttui/tests/smoke.cpp | 47 +- ui/ttui/tests/smoke.vcxproj | 5 +- 63 files changed, 2185 insertions(+), 100 deletions(-) create mode 100644 client/README.md rename client/src/{ => app}/startup_options.h (91%) rename client/src/{ => engine}/download_engine.cpp (83%) rename client/src/{ => engine}/download_engine.h (86%) create mode 100644 client/src/engine/download_link.h create mode 100644 client/src/engine/torrent_backend.cpp create mode 100644 client/src/engine/torrent_backend.h delete mode 100644 client/src/http_transport.cpp rename client/src/{ => integration}/client_browser_bridge.cpp (92%) rename client/src/{ => integration}/client_browser_bridge.h (81%) rename client/src/{ => integration}/external_download.h (100%) rename client/src/{ => integration}/file_drop_source.cpp (99%) rename client/src/{ => integration}/file_drop_source.h (100%) rename client/src/{ => platform}/platform.h (100%) create mode 100644 client/src/settings/proxy_settings.h rename client/src/{ => settings}/skin_settings.h (100%) create mode 100644 client/src/settings/tracker_import.cpp create mode 100644 client/src/settings/tracker_import.h create mode 100644 client/src/settings/tracker_settings.h rename client/src/{ => storage}/task_store.cpp (98%) rename client/src/{ => storage}/task_store.h (100%) create mode 100644 client/src/transport/ftp_transport.cpp create mode 100644 client/src/transport/ftp_transport.h create mode 100644 client/src/transport/http_transport.cpp rename client/src/{ => transport}/http_transport.h (100%) rename client/src/{ => transport}/winhttp_transport.cpp (98%) rename client/src/{ => transport}/winhttp_transport.h (69%) rename client/src/{ => ui}/add_task_form.cpp (97%) rename client/src/{ => ui}/add_task_form.h (96%) rename client/src/{ => ui}/downloader_form.cpp (91%) rename client/src/{ => ui}/downloader_form.h (90%) create mode 100644 client/src/ui/proxy_form.cpp create mode 100644 client/src/ui/proxy_form.h rename client/src/{ => ui}/settings_form.cpp (99%) rename client/src/{ => ui}/settings_form.h (95%) create mode 100644 client/src/ui/tracker_form.cpp create mode 100644 client/src/ui/tracker_form.h create mode 100644 client/tests/protocol_tests.cpp create mode 100644 client/tests/protocol_tests.vcxproj create mode 100644 client/tests/proxy_fixture.py create mode 100644 client/tests/run_protocol_tests.py create mode 100644 client/ttdownloader.vcxproj.filters create mode 100644 third_party/CMakeLists.txt create mode 100644 third_party/NOTICES.txt create mode 100644 third_party/README.md create mode 100644 third_party/build-openssl.ps1 create mode 100644 third_party/dependencies.props create mode 100644 third_party/prepare.ps1 diff --git a/.gitignore b/.gitignore index b786d90..4695ff7 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,17 @@ ui/ttui/obj/ # Browser host intermediates browser/native/obj/ browser/tests/obj/ + +# Reproducibly bootstrapped protocol dependencies +third_party/sources/ +third_party/build/ +third_party/curl-8.23.0/ +third_party/libtorrent-rasterbar-2.0.11/ +third_party/boost_1_86_0/ + +third_party/openssl-3.5.9/ +third_party/openssl/ + +# Python test cache +__pycache__/ +*.pyc diff --git a/AGENTS.md b/AGENTS.md index 81da51b..de1be7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ - 桌面客户端目前采用**全 C++ 开发**,不要引入 C#、WPF、WinUI、Electron 或 .NET 作为替代方案。 - 使用现代 C++,默认以 **C++20、MSVC、Windows 7 SP1 及以上 x64** 为开发基线。 -- 除非特别说明,所有窗口默认大小固定,不允许拖动边框调整大小或最大化;DPI 变化时仍须正确缩放。 +- 主窗口允许拖动边框调整大小和最大化,初始客户区 940×640,最小客户区 760×420(按 DPI 缩放);左侧导航、任务视口、滚动条和底部操作须随窗口尺寸更新。其余窗口除非特别说明仍默认固定大小,不允许调整大小或最大化;DPI 变化时须正确缩放。 - 最低兼容 Windows 7 SP1 x64;较新系统 API 必须动态解析并提供 Windows 7 回退,不得在导入表中硬依赖。兼容性发布须在 Windows 7 实机或虚拟机验证。 - 所有应用窗口统一使用窗口透明度设置,默认 100%、最低 30%;新建窗口显示前须应用该设置,拖动滑块同步预览,保存与背景覆盖设置分开。 - 控件默认不绘制独立背景色,沿用窗口背景;按钮须保留可辨识边框、居中文字及焦点/悬停/按下反馈,不得退化为纯文字链接;焦点提示不使用文字下划线。进度控件保留必要的进度指示。 @@ -52,10 +52,10 @@ ## HTTP 传输层边界 -- `client/src/http_transport.h` 定义不含 Windows/WinHTTP 原生句柄的请求、响应和同步流接口;传输层不依赖 TaskInfo、TaskStore、窗口或下载任务命令。 -- `client/src/winhttp_transport.cpp` 封装当前 WinHTTP 实现,负责 URL 解析、请求、响应头、网络数据读取及网络错误。HTTP 404/416 等状态原样交给调用方处理。 +- `client/src/transport/http_transport.h` 定义不含 Windows/WinHTTP 原生句柄的请求、响应和同步流接口;传输层不依赖 TaskInfo、TaskStore、窗口或下载任务命令。 +- `client/src/transport/winhttp_transport.cpp` 封装当前 WinHTTP 实现,负责 URL 解析、请求、响应头、网络数据读取及网络错误。HTTP 404/416 等状态原样交给调用方处理。 - `DownloadEngine` 只依赖传输接口,负责排队、文件写入、200/206/416 续传策略、重试、取消、进度和数据库节流;禁止在引擎中直接调用 WinHTTP API。 -- 默认后端在 `client/src/http_transport.cpp` 组装;以后迁移 libcurl 时实现同一接口并修改此入口。引擎支持注入 Transport,便于测试和后端替换。 +- 默认后端在 `client/src/transport/http_transport.cpp` 组装;以后迁移 libcurl 时实现同一接口并修改此入口。引擎支持注入 Transport,便于测试和后端替换。 - Open/Read 是工作线程上的同步操作,暂停和退出在操作边界检查;每次操作有超时,不允许传输层自行重试、回调 UI 或访问数据库。响应流应在同一工作线程中销毁,确保网络句柄及时释放。 - `test.cmd Debug/Release` 包含仅绑定 127.0.0.1 的 HTTP 集成测试,不连接外部网站,不访问用户任务库。 @@ -67,7 +67,7 @@ - 版本与来源:`third_party/sqlite3/` 存放官方 amalgamation(当前 `SQLITE_VERSION` 为 3.54.1,即 `sqlite3.c` + `sqlite3.h` 两个文件)。版本以文件头注释为准;下载页为 ,源码仓库为 (官方自托管在 )。 - 集成方式:`sqlite3.c` 直接加入 `client/ttdownloader.vcxproj` 编译(关闭预编译头、关闭该文件警告),头文件搜索路径指向 `third_party/sqlite3`。不引入 ORM 或其他 SQLite 封装库。 -- 访问入口:业务代码只通过 `client/src/task_store.h` 的 `TaskStore` 读写数据库,不直接调用 `sqlite3_*` API。 +- 访问入口:业务代码只通过 `client/src/storage/task_store.h` 的 `TaskStore` 读写数据库,不直接调用 `sqlite3_*` API。 - 数据库位置:`%LOCALAPPDATA%\TTDownloader\tasks.db`,由下载引擎线程打开;连接参数固定为 `journal_mode=WAL`、`synchronous=NORMAL`、`busy_timeout=5000`。 - 线程约定:数据库只在下载引擎工作线程(`DownloadEngine::ThreadMain`)内访问,UI 线程不得直接读写;引擎通过 `EngineEvent` 把状态回传给 UI。 - 写入节流:进度(`UpdateProgress`)每 3 秒落库一次;新增、暂停、完成、失败等状态变更(`UpdateState`)立即写入。不要按下载块或 UI 刷新频率写库。 @@ -97,3 +97,32 @@ - BT/磁力在基础下载链路稳定后接入 libtorrent。 - P2SP、资源调度服务器不属于当前短期目标。UI 引擎按独立模块、逐步替换的方式推进,第一阶段不要求完整复刻 Bolt。 - 新引入第三方 C/C++ 库前,先确认维护状态、Windows/MSVC 兼容性和许可证。 + +## FTP 与磁力后端 + +- HTTP/HTTPS 直连使用 WinHTTP,启用应用代理时使用 libcurl;FTP/FTPS 由 `ftp_transport.cpp` 的 libcurl 流实现,仍通过原有传输接口交给工作线程写文件。REST 不受支持时必须明确从零重下,不得拼接错误内容。 +- 磁力由 `torrent_backend.cpp` 的 libtorrent 独立管理元数据、文件块与恢复;不可使用 HTTP 顺序写文件路径。任务文件保存在独立目录,恢复快照按 task_id 保存;暂停和状态入库仍由引擎线程执行。 +- 当前不接入 ed2k;浏览器自动接管仍限 HTTP/HTTPS。磁力暂不后台做种,删除任务保留文件并在界面明确说明。 +- 新依赖由 third_party/prepare.ps1 固定来源、版本及 SHA-256 构建,发布必须附带 third_party/NOTICES.txt。Windows 7 编译目标不替代实机验证;libtorrent 静态接入 OpenSSL 3.5.9,HTTPS Tracker 必须验证证书并使用 Windows ROOT 信任库,不得关闭校验。 + +## Tracker 设置 + +- 设置菜单中的 Tracker 页面为独立固定大小窗口,使用原生多行输入框;Enter 必须换行,不能触发保存。窗口沿用全局透明度和背景配置。 +- Tracker 设置接受 UDP/HTTP/HTTPS,校验并去重后保存到当前用户 Software/TTDownloader 的 Trackers。 +- 下载引擎通过命令队列更新当前磁力会话,重新 announce;UI 不可直接调用 libtorrent。自定义列表替换时保留磁力原始 Tracker,但不能把恢复文件中的旧全局列表重新带回来。 +- 元数据等待状态显示连接节点、DHT 节点和 Tracker 数量及反馈;Tracker 无资源或网络受限时不能声称必然可以下载。回归测试使用本机 HTTP Tracker,不访问公网、用户数据库或修改用户 Tracker 设置。 + +- Tracker TXT 导入支持本地文件和 HTTP/HTTPS 在线文本,每行一个地址;后台读取,兼容 UTF-8 BOM/UTF-16 BOM 与系统 ANSI。导入追加到当前编辑列表并去重,明确统计跳过的无效条目;不自动保存或应用。关闭窗口取消导入,不得把旧结果写入重建后的窗口。在线回归仅使用本机 HTTP 服务。 + +## 代理设置 + +- 设置菜单提供直连、HTTP、SOCKS5,支持用户名/密码,统一用于 HTTP/FTP、Tracker 在线导入及磁力;代理失败不得回退直连。 +- 配置使用当前用户 DPAPI 加密写入 HKCU/Software/TTDownloader/ProxyDPAPI,不记录明文密码;损坏或无法解密时必须明确失败。 +- 保存后通过引擎命令重建磁力会话并关闭旧连接;现有 HTTP/FTP 流暂停继续后使用新配置。SOCKS5 使用代理端 DNS;HTTP 代理模式停用 UDP Tracker 和 DHT,SOCKS5 UDP 取决于服务端能力。 +- 回归仅使用本机认证代理,覆盖续传、FTP、远端 DNS 和不可信证书拒绝,不修改用户配置或系统证书库。 + +- Tracker 列表不得设置任意条数、总字符数、单 URL 长度或 TXT 文件大小上限;导入、编辑、保存、加载及引擎应用须保持完整一致。仅遵守底层系统接口的可表示容量并处理内存/系统调用失败,不得静默截断或伪称协议限制。 + +## 客户端目录约定 + +- `client/src/` 按 app、ui、engine、transport、storage、settings、integration、platform 分层;入口及预编译头留在根目录。新增文件按职责归档,跨模块头文件使用相对 src 的目录前缀,并同步更新工程、筛选器和测试路径。详见 `client/README.md`。 diff --git a/browser/README.md b/browser/README.md index 6e7bd57..fd8860d 100644 --- a/browser/README.md +++ b/browser/README.md @@ -67,3 +67,21 @@ Host 限制扩展来源和 64KiB 消息长度,按原生消息协议使用 4 覆盖扩展过滤、确认前不取消、离线/重复/断线恢复、恢复失败、后台重启、用户恢复下载、实际后台事件接线;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)。 + +## 桌面端新增协议 + +客户端添加窗口和命令行可接受 `ftp://`、`ftps://` 和 `magnet:?` 地址。浏览器扩展本次仍只接管 HTTP/HTTPS GET,未扩大自动拦截范围。 + +FTP 使用 libcurl,支持被动模式和断点续传;磁力使用 libtorrent,支持元数据获取、分块校验、暂停和恢复。磁力多文件保存在独立 BT 目录,删除任务时保留文件;暂不后台做种。更多构建及兼容性边界见 `third_party/README.md`。 + +## Tracker 设置 + +打开客户端“设置 → Tracker 设置”,每行粘贴一个 `udp://` 或 `http://` Tracker,点击“保存并应用”。“默认列表”按钮填入内置 UDP 列表,仍需保存才生效。保存会更新正在运行的磁力任务并重新寻找节点,暂停或排队任务在恢复/开始时使用最新配置;磁力链接原有的 Tracker 会保留。清空列表后保存仅停用全局补充列表,不会移除原链接的 Tracker。 + +获取元数据时会显示已连接节点数、DHT 节点数、Tracker 数量及 Tracker 失败反馈。现已通过 OpenSSL 支持 HTTPS Tracker,并验证服务端证书。Tracker 不能替代资源节点;资源无人提供或 UDP 网络受限时仍可能等待。测试只验证本机 Tracker 的热更新及实际取回元数据,不证明任何公网 Tracker 对特定资源可用。 + +Tracker 设置提供“在线导入”和“本地导入”。在线输入返回纯文本的 HTTP/HTTPS 地址,本地选择 TXT;每行一个 Tracker,支持 UTF-8(可带 BOM)、UTF-16(带 BOM)及系统 ANSI。导入会追加去重,并分别显示新增、重复、无效数量;无效条目会跳过。应用不设置 Tracker 条数、列表长度或 TXT 文件大小上限,系统资源或读取失败时保留原列表,导入成功后仍需点击“保存并应用”。 + +## 代理 + +设置菜单 → 代理设置,可选择直连、HTTP 或 SOCKS5,并填写地址、端口及可选账号密码。设置使用 Windows 当前用户 DPAPI 加密保存,覆盖磁力、HTTP/FTP 下载和 Tracker 在线导入。保存后磁力重新连接;已建立的 HTTP/FTP 下载需暂停后继续。HTTP 代理不能承载 UDP Tracker/DHT;SOCKS5 是否支持 UDP 由服务端决定,节点连接使用 TCP。代理失败不会回退直连。 diff --git a/browser/tests/bridge_tests.cpp b/browser/tests/bridge_tests.cpp index e67f51a..a696477 100644 --- a/browser/tests/bridge_tests.cpp +++ b/browser/tests/bridge_tests.cpp @@ -2,7 +2,7 @@ #include "../shared/pipe.h" #include "../native/client_connection.h" #include "../shared/command_line.h" -#include "../../client/src/startup_options.h" +#include "../../client/src/app/startup_options.h" #include #include #include diff --git a/browser/tests/browser_bridge_tests.vcxproj b/browser/tests/browser_bridge_tests.vcxproj index e86b843..7c22e3e 100644 --- a/browser/tests/browser_bridge_tests.vcxproj +++ b/browser/tests/browser_bridge_tests.vcxproj @@ -10,7 +10,7 @@ $(ProjectDir)..\..\client\bin\tests\$(Configuration)\$(ProjectDir)obj\$(Configuration)\browser_bridge_tests - + $(ProjectDir)..\..\client\src;%(AdditionalIncludeDirectories) stdcpp20/utf-8 %(AdditionalOptions)Sync NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions) MultiThreadedDebug diff --git a/build.cmd b/build.cmd index 0805e7b..ccd5822 100644 --- a/build.cmd +++ b/build.cmd @@ -11,6 +11,9 @@ if not defined MSBUILD ( exit /b 1 ) +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0third_party\prepare.ps1" -Configuration %CONFIG% +if errorlevel 1 exit /b 1 "%MSBUILD%" "%~dp0TTDownloader.sln" -p:Configuration=%CONFIG% -p:Platform=x64 -p:PlatformToolset=v143 -m -v:minimal set "BUILD_EXIT_CODE=%ERRORLEVEL%" +if "%BUILD_EXIT_CODE%"=="0" copy /y "%~dp0third_party\NOTICES.txt" "%~dp0client\bin\THIRD-PARTY-NOTICES.txt" >nul endlocal & exit /b %BUILD_EXIT_CODE% diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..4453fcc --- /dev/null +++ b/client/README.md @@ -0,0 +1,16 @@ +# 客户端源码结构 + +`src/main.cpp` 为程序入口,`stdafx.*` 为预编译头;头文件以 `src` 为包含路径根,跨模块引用使用目录前缀。 + +| 目录 | 职责 | +| --- | --- | +| app | 启动参数、单实例启动请求 | +| ui | 下载器业务窗口和页面;通用控件仍在 `ui/ttui/` | +| engine | 任务调度、链接识别、磁力后端 | +| transport | HTTP/HTTPS、FTP/FTPS 传输接口与实现 | +| storage | TaskStore 与任务持久化 | +| settings | 外观、代理、Tracker 配置及 TXT 导入 | +| integration | 浏览器桥接、外部下载请求、文件拖放 | +| platform | Windows 平台辅助函数 | + +`tests/` 存放客户端回归测试。Visual Studio 工程及筛选器按相同目录组织。 diff --git a/client/src/startup_options.h b/client/src/app/startup_options.h similarity index 91% rename from client/src/startup_options.h rename to client/src/app/startup_options.h index 540928d..05893d9 100644 --- a/client/src/startup_options.h +++ b/client/src/app/startup_options.h @@ -1,6 +1,7 @@ #pragma once -#include "platform.h" -#include "../../browser/shared/protocol.h" +#include "platform/platform.h" +#include "engine/download_link.h" +#include "../../../browser/shared/protocol.h" #include #include struct StartupOptions { @@ -36,7 +37,7 @@ inline bool ParseStartupCommandLine(const std::wstring& command,StartupOptions& result.show_add=true; result.url=args[0]; } const auto url=platform::ToUtf8(result.url); std::string error; - return !url.empty() && browser_bridge::Validate({{"action","add"},{"request_id","cli"},{"method","GET"},{"url",url}},error); + return IsLocalDownloadLink(result.url); } inline bool DecodeStartupCopyData(const COPYDATASTRUCT* data,StartupOptions& result) { if (!data || data->dwData!=kStartupCopyDataTag || !data->lpData || data->cbData #include @@ -276,6 +279,16 @@ std::shared_ptr DownloadEngine::SubmitExternal(ExternalDownl cmd_cv_.notify_all(); return state; } +void DownloadEngine::RefreshProxy() { + Command command; command.kind=Command::kProxy; + { std::lock_guard lock(cmd_mutex_); commands_.push_back(std::move(command)); } cmd_cv_.notify_all(); +} +void DownloadEngine::ConfigureTrackers(const std::vector& urls) { + Command command; command.kind=Command::kTrackers; command.trackers=urls; + { std::lock_guard lock(cmd_mutex_); commands_.push_back(std::move(command)); } + cmd_cv_.notify_all(); +} + void DownloadEngine::PauseTask(int64_t id) { Command cmd; @@ -315,6 +328,7 @@ void DownloadEngine::DeleteTask(int64_t id, bool delete_file) void DownloadEngine::ThreadMain() { + std::wstring tracker_error; ParseTrackers(LoadTrackers(),trackers_,tracker_error); std::wstring local_data = platform::LocalAppData(); if (local_data.empty()) { auto* event = new EngineEvent; @@ -350,7 +364,7 @@ void DownloadEngine::ThreadMain() if (task.state == TaskState::kQueued || task.state == TaskState::kDownloading) { task.state = TaskState::kQueued; - task.downloaded_bytes = GetFileSize(task.save_path + L".tdpart"); + if (!IsMagnet(task.url)) task.downloaded_bytes = GetFileSize(task.save_path + L".tdpart"); store_.UpdateState(task.id, TaskState::kQueued, task.downloaded_bytes, task.total_bytes, L""); queue_.push_back(task.id); @@ -425,6 +439,9 @@ void DownloadEngine::DrainCommands() { switch (cmd.kind) { + case Command::kProxy: ++proxy_revision_; break; + case Command::kTrackers: + trackers_=cmd.trackers; ++tracker_revision_; break; case Command::kAdd: HandleAdd(cmd); break; @@ -462,9 +479,11 @@ void DownloadEngine::HandleAdd(const Command& cmd) } http::UrlParts parts; - if (!transport_->ParseUrl(url, parts)) + std::wstring magnet_name,magnet_id; + const bool magnet=IsMagnet(url); + if (magnet?!ParseMagnet(url,magnet_name,magnet_id):!transport_->ParseUrl(url, parts)) { - reject(L"仅支持有效的 HTTP/HTTPS 链接"); + reject(L"请输入有效的 HTTP/HTTPS、FTP/FTPS 或磁力链接"); return; } @@ -477,7 +496,9 @@ void DownloadEngine::HandleAdd(const Command& cmd) 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) + std::wstring other_name,other_id; + bool same_magnet=magnet && IsMagnet(entry.second.url) && ParseMagnet(entry.second.url,other_name,other_id) && other_id==magnet_id; + if (entry.second.url == url || same_magnet) { if (!cmd.external.request_id.empty() && entry.second.request_id==cmd.external.request_id) reply("accepted",L"此请求已接管",entry.first); @@ -499,13 +520,13 @@ void DownloadEngine::HandleAdd(const Command& cmd) TaskInfo task; task.url = url; - task.file_name = FileNameFromUrl(url,*transport_); + task.file_name = magnet?SanitizeFileName(magnet_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.save_path = PickUniquePath(dir, magnet?L"BT-"+magnet_id.substr(0,16):task.file_name, tasks_); task.state = TaskState::kQueued; if (!store_open_ || !store_.Insert(task)) @@ -543,7 +564,7 @@ void DownloadEngine::HandlePause(int64_t id) queue_.erase(std::remove(queue_.begin(), queue_.end(), id), queue_.end()); it->second.state = TaskState::kPaused; - it->second.downloaded_bytes = GetFileSize(it->second.save_path + L".tdpart"); + if (!IsMagnet(it->second.url)) it->second.downloaded_bytes = GetFileSize(it->second.save_path + L".tdpart"); if (store_open_) store_.UpdateState(id, TaskState::kPaused, it->second.downloaded_bytes, it->second.total_bytes, L""); @@ -573,7 +594,7 @@ void DownloadEngine::HandleResume(int64_t id) TaskInfo& task = it->second; task.state = TaskState::kQueued; task.error.clear(); - task.downloaded_bytes = GetFileSize(task.save_path + L".tdpart"); + if (!IsMagnet(task.url)) task.downloaded_bytes = GetFileSize(task.save_path + L".tdpart"); if (store_open_) store_.UpdateState(task.id, TaskState::kQueued, task.downloaded_bytes, task.total_bytes, L""); @@ -616,8 +637,52 @@ void DownloadEngine::HandleDelete(int64_t id, bool delete_file) PostEvent(event); } +void DownloadEngine::DownloadTorrent(TaskInfo& task) { + const auto resume=platform::LocalAppData()+L"\\TTDownloader\\resume\\"+std::to_wstring(task.id)+L".resume"; + TorrentTransfer transfer(task.url,task.save_path,resume,false,trackers_); + auto tracker_revision=tracker_revision_,proxy_revision=proxy_revision_; + task.state=TaskState::kDownloading; task.error.clear(); + store_.UpdateState(task.id,task.state,task.downloaded_bytes,task.total_bytes,L""); + auto last_save=GetTickCount64(),last_resume=last_save-30000; + while (!stop_ && !cancel_current_) { + DrainCommands(); if (stop_ || cancel_current_) break; + if (proxy_revision!=proxy_revision_) { transfer.RefreshProxy(); proxy_revision=proxy_revision_; } + if (tracker_revision!=tracker_revision_) { transfer.SetTrackers(trackers_); tracker_revision=tracker_revision_; } + auto progress=transfer.Poll(); + if (!progress.error.empty()) { transfer.Save(); Fail(task,progress.error); return; } + task.downloaded_bytes=progress.downloaded; task.total_bytes=progress.total; + task.error=progress.diagnostic; + if (!progress.name.empty()) { + auto name=SanitizeFileName(progress.name); + if (name!=task.file_name) { task.file_name=std::move(name); store_.UpdateTarget(task.id,task.save_path,task.file_name); } + } + if (progress.total>0 && GetTickCount64()-last_resume>=30000) { + transfer.Save(false); last_resume=GetTickCount64(); + } + PostUpdate(task,progress.speed); + if (GetTickCount64()-last_save>=3000) { + store_.UpdateProgress(task.id,task.downloaded_bytes,task.total_bytes); last_save=GetTickCount64(); + } + if (progress.complete) { + transfer.Save(); task.state=TaskState::kCompleted; + store_.UpdateTarget(task.id,task.save_path,task.file_name); + store_.UpdateState(task.id,task.state,task.downloaded_bytes,task.total_bytes,L""); PostUpdate(task,0); return; + } + std::unique_lock lock(cmd_mutex_); cmd_cv_.wait_for(lock,std::chrono::milliseconds(200),[&] { return stop_ || !commands_.empty(); }); + } + transfer.Save(); + if (!removed_current_) { + auto final=transfer.Poll(); + if (final.error.empty()) { task.downloaded_bytes=final.downloaded; task.total_bytes=final.total; } + + task.state=TaskState::kPaused; + store_.UpdateState(task.id,task.state,task.downloaded_bytes,task.total_bytes,L""); PostUpdate(task,0); + } +} + void DownloadEngine::Download(TaskInfo& task) { + if (IsMagnet(task.url)) { DownloadTorrent(task); return; } const std::wstring part_path = task.save_path + L".tdpart"; task.downloaded_bytes = GetFileSize(part_path); @@ -815,7 +880,7 @@ DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task, } } - if (task.total_bytes > 0 && downloaded < task.total_bytes) + if (task.total_bytes > 0 && (downloaded < task.total_bytes || (IsFtp(task.url) && downloaded != task.total_bytes))) { error = L"连接提前中断"; return AttemptResult::kRetry; diff --git a/client/src/download_engine.h b/client/src/engine/download_engine.h similarity index 86% rename from client/src/download_engine.h rename to client/src/engine/download_engine.h index 766429f..597aac1 100644 --- a/client/src/download_engine.h +++ b/client/src/engine/download_engine.h @@ -2,9 +2,9 @@ #include -#include "task_store.h" -#include "http_transport.h" -#include "external_download.h" +#include "storage/task_store.h" +#include "transport/http_transport.h" +#include "integration/external_download.h" #include #include @@ -49,6 +49,8 @@ public: void AddTask(const std::wstring& url, const std::wstring& save_dir); void PauseTask(int64_t id); + void ConfigureTrackers(const std::vector&); + void RefreshProxy(); void ResumeTask(int64_t id); void DeleteTask(int64_t id, bool delete_file); @@ -63,12 +65,15 @@ private: kDelete, kPause, kResume, + kTrackers, + kProxy, }; Kind kind = kAdd; int64_t id = 0; bool delete_file = false; std::wstring url; std::wstring save_dir; + std::vector trackers; ExternalDownload external; std::shared_ptr submission; }; @@ -88,6 +93,7 @@ private: void HandleResume(int64_t id); void HandleDelete(int64_t id, bool delete_file); void Download(TaskInfo& task); + void DownloadTorrent(TaskInfo& task); AttemptResult RunAttempt(TaskInfo& task, const std::wstring& part_path, std::wstring& error); void Fail(TaskInfo& task, const std::wstring& error); bool WaitBeforeRetry(); @@ -109,6 +115,8 @@ private: // 以下成员只由下载线程访问 TaskStore store_; bool store_open_ = false; + std::vector trackers_; + uint64_t tracker_revision_=0,proxy_revision_=0; std::map tasks_; std::deque queue_; int64_t current_id_ = 0; diff --git a/client/src/engine/download_link.h b/client/src/engine/download_link.h new file mode 100644 index 0000000..c73e89e --- /dev/null +++ b/client/src/engine/download_link.h @@ -0,0 +1,12 @@ +#pragma once +#include +inline bool IsMagnet(const std::wstring& url) { return url.rfind(L"magnet:?",0)==0; } +inline bool IsFtp(const std::wstring& url) { return url.rfind(L"ftp://",0)==0 || url.rfind(L"ftps://",0)==0; } +inline bool IsLocalDownloadLink(const std::wstring& url) { + if(url.empty() || url.size()>16384 || url.find_first_of(L"\r\n\t ")!=std::wstring::npos) return false; + if(IsMagnet(url)) return url.find(L"xt=urn:btih:")!=std::wstring::npos || url.find(L"xt=urn:btmh:")!=std::wstring::npos; + size_t start=url.rfind(L"https://",0)==0?8:url.rfind(L"http://",0)==0?7:url.rfind(L"ftps://",0)==0?7:url.rfind(L"ftp://",0)==0?6:0; + if(!start) return false; + auto end=url.find_first_of(L"/?#",start); auto host=url.substr(start,end==std::wstring::npos?end:end-start); + return !host.empty() && (IsFtp(url) || host.find(L'@')==std::wstring::npos); +} diff --git a/client/src/engine/torrent_backend.cpp b/client/src/engine/torrent_backend.cpp new file mode 100644 index 0000000..9bd0471 --- /dev/null +++ b/client/src/engine/torrent_backend.cpp @@ -0,0 +1,142 @@ +#include "stdafx.h" +#include "engine/torrent_backend.h" +#include "platform/platform.h" +#include "settings/proxy_settings.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace lt=libtorrent; +bool ParseMagnet(const std::wstring& url,std::wstring& name,std::wstring& identity) { + if(url.size()>16384 || url.find_first_of(L"\r\n\t ")!=std::wstring::npos) return false; + lt::error_code error; auto params=lt::parse_magnet_uri(platform::ToUtf8(url),error); + if(error || !params.info_hashes.has_v1() && !params.info_hashes.has_v2()) return false; + identity=platform::FromUtf8(lt::aux::to_hex(params.info_hashes.has_v1()?params.info_hashes.v1.to_string():params.info_hashes.v2.to_string())); + name=params.name.empty()?L"磁力下载 "+identity.substr(0,12):platform::FromUtf8(params.name); return true; +} +namespace { +void ProxyOptions(lt::settings_pack& settings,const ProxySettings& proxy,bool local_only) { + std::wstring error; if(!ValidateProxy(proxy,error)) throw std::runtime_error("Invalid proxy configuration"); + int type=proxy.type==2?(proxy.user.empty()?lt::settings_pack::socks5:lt::settings_pack::socks5_pw):proxy.type==1?(proxy.user.empty()?lt::settings_pack::http:lt::settings_pack::http_pw):lt::settings_pack::none; + settings.set_int(lt::settings_pack::proxy_type,type); settings.set_int(lt::settings_pack::proxy_port,proxy.type?std::stoi(proxy.port):0); + auto host=proxy.host; if(host.size()>2 && host.front()==L'[' && host.back()==L']') host=host.substr(1,host.size()-2); + settings.set_str(lt::settings_pack::proxy_hostname,platform::ToUtf8(host)); settings.set_str(lt::settings_pack::proxy_username,platform::ToUtf8(proxy.user)); settings.set_str(lt::settings_pack::proxy_password,platform::ToUtf8(proxy.password)); + settings.set_bool(lt::settings_pack::proxy_hostnames,true); settings.set_bool(lt::settings_pack::proxy_peer_connections,true); settings.set_bool(lt::settings_pack::proxy_tracker_connections,true); + settings.set_bool(lt::settings_pack::enable_dht,!local_only && proxy.type!=1); + // Proxy peer traffic uses TCP; UDP relay remains available to DHT/trackers. + settings.set_bool(lt::settings_pack::enable_outgoing_utp,proxy.type==0); + settings.set_str(lt::settings_pack::listen_interfaces,local_only?"127.0.0.1:0":"0.0.0.0:0,[::]:0"); +} +} +struct TorrentTransfer::Impl { + std::unique_ptr session; lt::torrent_handle handle; std::wstring resume,magnet,directory; std::vector custom_trackers; bool local_only=false; std::wstring error,tracker_error; std::vector original_trackers; struct DhtCount { int nodes; ULONGLONG seen; }; std::map dht_counts; int dht_nodes=0; ULONGLONG dht_poll=0; +}; +TorrentTransfer::TorrentTransfer(const std::wstring& magnet,const std::wstring& directory,const std::wstring& resume,bool local_only,const std::vector& trackers):impl_(std::make_unique()) { + impl_->resume=resume; impl_->magnet=magnet; impl_->directory=directory; impl_->local_only=local_only; + try { + lt::error_code ec; auto params=lt::parse_magnet_uri(platform::ToUtf8(magnet),ec); + if(ec) { impl_->error=platform::FromUtf8(ec.message()); return; } + for (const auto& tracker:params.trackers) impl_->original_trackers.emplace_back(tracker); + std::ifstream input(std::filesystem::path(resume),std::ios::binary|std::ios::ate); + if(input && input.tellg()>0 && input.tellg()<16*1024*1024) { + std::vector bytes(static_cast(input.tellg())); input.seekg(0); input.read(bytes.data(),bytes.size()); + auto saved=lt::read_resume_data(bytes,ec); + if(!ec && saved.info_hashes==params.info_hashes) params=std::move(saved); + } + params.trackers.clear(); params.tracker_tiers.clear(); + for (const auto& tracker:impl_->original_trackers) { params.trackers.push_back(tracker.url); params.tracker_tiers.push_back(0); } + params.save_path=platform::ToUtf8(directory); + params.flags &= ~lt::torrent_flags::auto_managed; params.flags &= ~lt::torrent_flags::paused; + lt::settings_pack settings; + settings.set_bool(lt::settings_pack::enable_dht,!local_only); + settings.set_str(lt::settings_pack::dht_bootstrap_nodes,local_only?"":"dht.libtorrent.org:25401,dht.transmissionbt.com:6881,router.bittorrent.com:6881"); + settings.set_bool(lt::settings_pack::announce_to_all_trackers,true); + settings.set_bool(lt::settings_pack::announce_to_all_tiers,true); + settings.set_bool(lt::settings_pack::enable_lsd,false); + settings.set_bool(lt::settings_pack::enable_upnp,false); + settings.set_bool(lt::settings_pack::enable_natpmp,false); + settings.set_str(lt::settings_pack::listen_interfaces,local_only?"127.0.0.1:0":"0.0.0.0:0,[::]:0"); + settings.set_int(lt::settings_pack::alert_mask,lt::alert_category::storage|lt::alert_category::error|lt::alert_category::status|lt::alert_category::tracker); + settings.set_bool(lt::settings_pack::validate_https_trackers,true); + ProxyOptions(settings,CurrentProxy(),local_only); + impl_->session=std::make_unique(settings); + impl_->handle=impl_->session->add_torrent(params,ec); + if(ec) impl_->error=platform::FromUtf8(ec.message()); + else SetTrackers(trackers); + } catch(const std::exception& e) { impl_->error=platform::FromUtf8(e.what()); } +} +TorrentTransfer::~TorrentTransfer()=default; +TorrentProgress TorrentTransfer::Poll() { + TorrentProgress result; result.error=impl_->error; + if(!result.error.empty() || !impl_->handle.is_valid()) return result; + if(GetTickCount64()-impl_->dht_poll>2000) { impl_->session->post_dht_stats(); impl_->dht_poll=GetTickCount64(); } + auto state=impl_->handle.status(); result.downloaded=state.total_wanted_done; result.total=state.total_wanted; + result.speed=state.download_payload_rate; result.complete=state.is_finished && state.has_metadata; + result.name=platform::FromUtf8(state.name); result.peers=state.num_peers; result.trackers=static_cast(impl_->handle.trackers().size()); + if(state.errc) result.error=platform::FromUtf8(state.errc.message()); + std::vector alerts; impl_->session->pop_alerts(&alerts); + for(auto* alert:alerts) { + if(auto* dht=lt::alert_cast(alert)) { int nodes=0; for(const auto& bucket:dht->routing_table) nodes+=bucket.num_nodes; impl_->dht_counts[dht->nid.to_string()]={nodes,GetTickCount64()}; } + if(auto* failed=lt::alert_cast(alert)) impl_->tracker_error=platform::FromUtf8(failed->error.message()); + if(lt::alert_cast(alert)) impl_->tracker_error.clear(); + } + impl_->dht_nodes=0; + for(auto it=impl_->dht_counts.begin();it!=impl_->dht_counts.end();) { + if(GetTickCount64()-it->second.seen>6000) it=impl_->dht_counts.erase(it); + else { impl_->dht_nodes+=it->second.nodes; ++it; } + } + result.diagnostic=std::to_wstring(result.peers)+L" 个已连接节点 · DHT "+std::to_wstring(impl_->dht_nodes)+L" · "+std::to_wstring(result.trackers)+L" 个 Tracker"; + if (!impl_->tracker_error.empty()) result.diagnostic+=L" · Tracker:"+impl_->tracker_error; + return result; +} +void TorrentTransfer::SetTrackers(const std::vector& urls) { + if(!impl_->handle.is_valid()) return; + impl_->custom_trackers=urls; + auto trackers=impl_->original_trackers; std::set seen; + for(const auto& tracker:trackers) seen.insert(tracker.url); + for(const auto& url:urls) { auto utf8=platform::ToUtf8(url); if(seen.insert(utf8).second) trackers.emplace_back(utf8); } + if(CurrentProxy().type==1) trackers.erase(std::remove_if(trackers.begin(),trackers.end(),[](const auto& t) { return t.url.rfind("udp://",0)==0; }),trackers.end()); + impl_->handle.replace_trackers(trackers); impl_->tracker_error.clear(); + impl_->handle.force_reannounce(); impl_->handle.force_dht_announce(); +} +void TorrentTransfer::RefreshProxy() { + const auto magnet=impl_->magnet,directory=impl_->directory,resume=impl_->resume; + const auto trackers=impl_->custom_trackers; const bool local=impl_->local_only; + Save(true); + impl_.reset(); // Drop all old direct sockets before establishing proxy connections. + TorrentTransfer replacement(magnet,directory,resume,local,trackers); impl_=std::move(replacement.impl_); +} +bool TorrentTransfer::Save(bool pause) { + if(!impl_->handle.is_valid()) return false; + if (pause) impl_->handle.pause(); + impl_->handle.save_resume_data(lt::torrent_handle::save_info_dict|lt::torrent_handle::flush_disk_cache); + auto deadline=GetTickCount64()+5000; + while(GetTickCount64()session->wait_for_alert(lt::milliseconds(100)); + std::vector alerts; impl_->session->pop_alerts(&alerts); + for(auto* alert:alerts) { + if(auto* saved=lt::alert_cast(alert)) { + auto bytes=lt::write_resume_data_buf(saved->params); + std::filesystem::path path(impl_->resume); std::error_code ec; + std::filesystem::create_directories(path.parent_path(),ec); + auto temp=path; temp+=L".tmp"; + std::ofstream output(temp,std::ios::binary|std::ios::trunc); output.write(bytes.data(),bytes.size()); output.close(); + if(!output) return false; + return MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=FALSE; + } + if(lt::alert_cast(alert)) return false; + } + } + return false; +} diff --git a/client/src/engine/torrent_backend.h b/client/src/engine/torrent_backend.h new file mode 100644 index 0000000..b832468 --- /dev/null +++ b/client/src/engine/torrent_backend.h @@ -0,0 +1,18 @@ +#pragma once +#include +#include +#include +#include +struct TorrentProgress { int64_t downloaded=0,total=0; double speed=0; bool complete=false; std::wstring error,name,diagnostic; int peers=0,trackers=0; }; +class TorrentTransfer { +public: + TorrentTransfer(const std::wstring& magnet,const std::wstring& directory,const std::wstring& resume_file,bool local_only=false,const std::vector& trackers={}); + ~TorrentTransfer(); + TorrentProgress Poll(); + bool Save(bool pause=true); + void SetTrackers(const std::vector&); + void RefreshProxy(); +private: + struct Impl; std::unique_ptr impl_; +}; +bool ParseMagnet(const std::wstring&,std::wstring& name,std::wstring& identity); diff --git a/client/src/http_transport.cpp b/client/src/http_transport.cpp deleted file mode 100644 index f7c7552..0000000 --- a/client/src/http_transport.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "stdafx.h" -#include "http_transport.h" -#include "winhttp_transport.h" -namespace http { -std::unique_ptr CreateDefaultTransport() { return CreateWinHttpTransport(); } -} diff --git a/client/src/client_browser_bridge.cpp b/client/src/integration/client_browser_bridge.cpp similarity index 92% rename from client/src/client_browser_bridge.cpp rename to client/src/integration/client_browser_bridge.cpp index 4ba585a..dae6bc9 100644 --- a/client/src/client_browser_bridge.cpp +++ b/client/src/integration/client_browser_bridge.cpp @@ -1,8 +1,8 @@ #include "stdafx.h" -#include "client_browser_bridge.h" -#include "download_engine.h" -#include "platform.h" -#include "../../browser/shared/protocol.h" +#include "integration/client_browser_bridge.h" +#include "engine/download_engine.h" +#include "platform/platform.h" +#include "../../../browser/shared/protocol.h" #include std::unique_ptr StartBrowserBridge(DownloadEngine& engine,HWND window) { auto server=std::make_unique(); diff --git a/client/src/client_browser_bridge.h b/client/src/integration/client_browser_bridge.h similarity index 81% rename from client/src/client_browser_bridge.h rename to client/src/integration/client_browser_bridge.h index b1d7ebc..8393d8e 100644 --- a/client/src/client_browser_bridge.h +++ b/client/src/integration/client_browser_bridge.h @@ -1,7 +1,7 @@ #pragma once -#include "../../browser/shared/pipe.h" +#include "../../../browser/shared/pipe.h" #include -#include "external_download.h" +#include "integration/external_download.h" class DownloadEngine; inline constexpr UINT kBrowserRequestMessage=WM_APP+4; struct BrowserDialogRequest { diff --git a/client/src/external_download.h b/client/src/integration/external_download.h similarity index 100% rename from client/src/external_download.h rename to client/src/integration/external_download.h diff --git a/client/src/file_drop_source.cpp b/client/src/integration/file_drop_source.cpp similarity index 99% rename from client/src/file_drop_source.cpp rename to client/src/integration/file_drop_source.cpp index c768979..2b7f17a 100644 --- a/client/src/file_drop_source.cpp +++ b/client/src/integration/file_drop_source.cpp @@ -1,5 +1,5 @@ #include "stdafx.h" -#include "file_drop_source.h" +#include "integration/file_drop_source.h" #include #include diff --git a/client/src/file_drop_source.h b/client/src/integration/file_drop_source.h similarity index 100% rename from client/src/file_drop_source.h rename to client/src/integration/file_drop_source.h diff --git a/client/src/main.cpp b/client/src/main.cpp index 3d2e3a2..cf8b2be 100644 --- a/client/src/main.cpp +++ b/client/src/main.cpp @@ -1,6 +1,6 @@ #include "stdafx.h" #include "ttui/application.h" -#include "downloader_form.h" +#include "ui/downloader_form.h" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, @@ -15,7 +15,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, const std::wstring command=GetCommandLineW(); StartupOptions startup; if (!ParseStartupCommandLine(command,startup)) { - MessageBoxW(nullptr,L"启动参数无效。\n用法:ttdownloader.exe --add \"https://example.com/file.zip\"\n也可直接传入下载地址,或使用 --add 打开空白添加窗口。",L"TTDownloader",MB_ICONERROR); + MessageBoxW(nullptr,L"启动参数无效。\n用法:ttdownloader.exe --add \"https://example.com/file.zip\"\n也可直接传入 HTTP/FTP/磁力下载地址,或使用 --add 打开空白添加窗口。",L"TTDownloader",MB_ICONERROR); return 1; } HANDLE instance_mutex = ::CreateMutexW(nullptr, TRUE, L"Local\\TTDownloader.SingleInstance"); @@ -49,7 +49,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, DownloaderForm form; int result=ttui::RunApplication([&] { - if (!form.Create(nullptr,DownloaderForm::kClassName.c_str(),L"TTDownloader",940,640,true)) { + if (!form.Create(nullptr,DownloaderForm::kClassName.c_str(),L"TTDownloader",940,640,true,true)) { MessageBoxW(nullptr,L"无法创建主窗口。",L"TTDownloader",MB_ICONERROR); return false; } form.CenterWindow(); form.ShowWindow(); form.OpenStartupRequest(startup); return true; diff --git a/client/src/platform.h b/client/src/platform/platform.h similarity index 100% rename from client/src/platform.h rename to client/src/platform/platform.h diff --git a/client/src/settings/proxy_settings.h b/client/src/settings/proxy_settings.h new file mode 100644 index 0000000..00cfc07 --- /dev/null +++ b/client/src/settings/proxy_settings.h @@ -0,0 +1,61 @@ +#pragma once +#include +#include +#include +#include +#include +#pragma comment(lib,"crypt32.lib") +#pragma comment(lib,"advapi32.lib") +struct ProxySettings { int type=0; std::wstring host,port=L"1080",user,password; bool operator==(const ProxySettings&) const=default; }; +inline bool ValidateProxy(const ProxySettings& value,std::wstring& error) { + if(value.type<0 || value.type>2) { error=L"代理配置无效或无法解密,请重新保存"; return false; } + for(const auto* field:{&value.host,&value.port,&value.user,&value.password}) { + if(field->size()>1024) { error=L"代理字段过长"; return false; } + for(auto c:*field) if(c<32 || c==127) { error=L"代理字段不能包含控制字符"; return false; } + } + if(value.type==0) return true; + if(value.host.empty() || value.host.size()>253 || value.host.find_first_of(L" /\\@?#\r\n\t")!=std::wstring::npos) { error=L"请输入主机名或 IP,不含协议和端口"; return false; } + if(value.host.find(L':')!=std::wstring::npos && value.host.find(L':')==value.host.rfind(L':')) { error=L"端口请填在独立端口框中"; return false; } + unsigned port=0; if(value.port.empty() || value.port.size()>5) { error=L"代理端口无效"; return false; } + for(auto c:value.port) { if(cL'9') { error=L"代理端口无效"; return false; } port=port*10+c-L'0'; } + if(!port || port>65535) { error=L"代理端口超出范围"; return false; } + for(const auto* text:{&value.user,&value.password}) { if(text->size()>255) { error=L"代理账号或密码过长"; return false; } for(auto c:*text) if(c<32 || c==127) { error=L"代理账号密码不能包含控制字符"; return false; } } + return true; +} +inline ProxySettings LoadProxy() { + HKEY key=nullptr; auto opened=RegOpenKeyExW(HKEY_CURRENT_USER,L"Software\\TTDownloader",0,KEY_QUERY_VALUE,&key); + if(opened==ERROR_FILE_NOT_FOUND || opened==ERROR_PATH_NOT_FOUND) return {}; + if(opened!=ERROR_SUCCESS) { ProxySettings invalid; invalid.type=-1; return invalid; } + DWORD type=0,size=0; auto status=RegQueryValueExW(key,L"ProxyDPAPI",nullptr,&type,nullptr,&size); + if(status==ERROR_FILE_NOT_FOUND) { RegCloseKey(key); return {}; } + ProxySettings invalid; invalid.type=-1; + if(status!=ERROR_SUCCESS || type!=REG_BINARY || size>16384 || !size) { RegCloseKey(key); return invalid; } + std::vector bytes(size); status=RegQueryValueExW(key,L"ProxyDPAPI",nullptr,&type,bytes.data(),&size); RegCloseKey(key); + if(status!=ERROR_SUCCESS) return invalid; + DATA_BLOB encrypted{size,bytes.data()},plain{}; + if(!CryptUnprotectData(&encrypted,nullptr,nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&plain)) return invalid; + std::wstring text; + if(plain.cbData%2==0) text.assign(reinterpret_cast(plain.pbData),plain.cbData/2); + SecureZeroMemory(plain.pbData,plain.cbData); LocalFree(plain.pbData); + std::vector parts; size_t begin=0; + for(int i=0;i<4;++i) { auto end=text.find(L'\n',begin); if(end==std::wstring::npos) return invalid; parts.push_back(text.substr(begin,end-begin)); begin=end+1; } + parts.push_back(text.substr(begin)); + ProxySettings result; result.type=parts[0]==L"0"?0:parts[0]==L"1"?1:parts[0]==L"2"?2:-1; + result.host=parts[1]; result.port=parts[2]; result.user=parts[3]; result.password=parts[4]; std::wstring error; + return ValidateProxy(result,error)?result:invalid; +} +inline bool SaveProxy(const ProxySettings& value) { + std::wstring error; if(!ValidateProxy(value,error)) return false; + auto text=std::to_wstring(value.type)+L"\n"+value.host+L"\n"+value.port+L"\n"+value.user+L"\n"+value.password; + DATA_BLOB plain{static_cast(text.size()*2),reinterpret_cast(text.data())},encrypted{}; + if(!CryptProtectData(&plain,L"TTDownloader proxy",nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&encrypted)) return false; + HKEY key=nullptr; bool saved=false; + if(RegCreateKeyExW(HKEY_CURRENT_USER,L"Software\\TTDownloader",0,nullptr,0,KEY_SET_VALUE,nullptr,&key,nullptr)==ERROR_SUCCESS) { + saved=RegSetValueExW(key,L"ProxyDPAPI",0,REG_BINARY,encrypted.pbData,encrypted.cbData)==ERROR_SUCCESS; RegCloseKey(key); + } + LocalFree(encrypted.pbData); return saved; +} +struct ProxyState { std::mutex mutex; ProxySettings value=LoadProxy(); }; +inline ProxyState& SharedProxyState() { static ProxyState state; return state; } +inline ProxySettings CurrentProxy() { auto& state=SharedProxyState(); std::lock_guard lock(state.mutex); return state.value; } +inline void SetCurrentProxy(ProxySettings value) { auto& state=SharedProxyState(); std::lock_guard lock(state.mutex); state.value=std::move(value); } diff --git a/client/src/skin_settings.h b/client/src/settings/skin_settings.h similarity index 100% rename from client/src/skin_settings.h rename to client/src/settings/skin_settings.h diff --git a/client/src/settings/tracker_import.cpp b/client/src/settings/tracker_import.cpp new file mode 100644 index 0000000..68bf996 --- /dev/null +++ b/client/src/settings/tracker_import.cpp @@ -0,0 +1,85 @@ +#include "stdafx.h" +#include "settings/tracker_import.h" +#include "settings/tracker_settings.h" +#include "transport/winhttp_transport.h" +#include "platform/platform.h" +#include +#include +#include +namespace { +bool Decode(const std::string& bytes,std::wstring& text) { + // Windows character conversion functions accept signed int lengths. + if(bytes.size()>static_cast((std::numeric_limits::max)())) return false; + if(bytes.size()>=2 && ((static_cast(bytes[0])==255 && static_cast(bytes[1])==254) + || (static_cast(bytes[0])==254 && static_cast(bytes[1])==255))) { + if(bytes.size()%2) return false; + bool little=static_cast(bytes[0])==255; + for(size_t i=2;i(bytes[i]),b=static_cast(bytes[i+1]); + text+=static_cast(little?(a|(b<<8)):((a<<8)|b)); + } + } else { + std::string raw=bytes; + if(raw.rfind("\xef\xbb\xbf",0)==0) raw.erase(0,3); + if(!raw.empty()) { + int size=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,raw.data(),static_cast(raw.size()),nullptr,0); + UINT page=CP_UTF8; DWORD flags=MB_ERR_INVALID_CHARS; + if(!size) { page=CP_ACP; flags=0; size=MultiByteToWideChar(page,flags,raw.data(),static_cast(raw.size()),nullptr,0); } + if(!size) return false; text.resize(size); + MultiByteToWideChar(page,flags,raw.data(),static_cast(raw.size()),text.data(),size); + } + } + return text.find(L'\0')==std::wstring::npos && (text.empty() || WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,text.data(),static_cast(text.size()),nullptr,0,nullptr,nullptr)>0); +} +} +TrackerImportResult ParseTrackerImport(const std::string& bytes,const std::wstring& current) { + TrackerImportResult result; std::wstring text; + if(!Decode(bytes,text)) { result.error=L"TXT 编码无效、含空字符或超出系统文本接口容量。"; return result; } + std::vector urls; std::wstring error; + if(!ParseTrackers(current,urls,error)) { result.error=L"请先修正编辑框中的列表:"+error; return result; } + std::set seen(urls.begin(),urls.end()); + size_t pos=0; + while(pos parsed; + if(!ParseTrackers(line,parsed,error)) { ++result.skipped; ++result.invalid; continue; } + if(parsed.empty()) continue; + const auto& url=parsed.front(); + if(seen.count(url)) { ++result.duplicates; continue; } + seen.insert(url); urls.push_back(url); ++result.added; + } + if(!result.added && !result.duplicates) { result.error=L"没有可导入的 Tracker:无效 "+std::to_wstring(result.invalid)+L" 条。"; return result; } + result.text=TrackerText(urls); return result; +} +TrackerImportResult ImportTrackerText(const std::wstring& source,bool online,const std::wstring& current,const std::atomic& canceled) { + TrackerImportResult result; std::string bytes; + if(canceled) { result.error=L"已取消导入"; return result; } + if(online) { + auto transport=http::CreateDefaultTransport(); http::UrlParts parts; + if(!transport->ParseUrl(source,parts)) { result.error=L"请输入 HTTP/HTTPS TXT 地址"; return result; } + auto start=source.find(L"://")+3; auto end=source.find_first_of(L"/?#",start); + if(source.substr(start,end==std::wstring::npos?end:end-start).find(L'@')!=std::wstring::npos || source.find_first_of(L"\r\n\t ")!=std::wstring::npos) { result.error=L"TXT 地址不能包含账号密码、空格或控制字符"; return result; } + http::Request request; request.url=source; request.timeouts={5000,5000,5000,3000}; + auto opened=transport->Open(request); + if(!opened.stream) { result.error=L"在线导入失败:"+opened.error; return result; } + if(opened.stream->Headers().status!=200) { result.error=L"服务器返回 HTTP "+std::to_wstring(opened.stream->Headers().status); return result; } + char buffer[8192]; auto deadline=GetTickCount64()+20000; + while(!canceled) { + if(GetTickCount64()>deadline) { result.error=L"在线导入超时"; return result; } + auto read=opened.stream->Read(buffer); + if(read.state==http::ReadState::kEnd) break; + if(read.state!=http::ReadState::kData || read.size==0 || read.size>sizeof(buffer)) { result.error=L"读取在线 TXT 失败:"+read.error; return result; } + bytes.append(buffer,read.size); + } + } else { + std::ifstream input(std::filesystem::path(source),std::ios::binary); + if(!input) { result.error=L"无法打开本地 TXT 文件"; return result; } + char buffer[8192]; + while(!canceled && input.read(buffer,sizeof(buffer))) bytes.append(buffer,sizeof(buffer)); + if(!canceled) bytes.append(buffer,static_cast(input.gcount())); + if(input.bad()) { result.error=L"读取本地 TXT 失败"; return result; } + } + if(canceled) { result.error=L"已取消导入"; return result; } + return ParseTrackerImport(bytes,current); +} diff --git a/client/src/settings/tracker_import.h b/client/src/settings/tracker_import.h new file mode 100644 index 0000000..be80e08 --- /dev/null +++ b/client/src/settings/tracker_import.h @@ -0,0 +1,7 @@ +#pragma once +#include +#include +#include +struct TrackerImportResult { std::wstring text,error; size_t added=0,duplicates=0,skipped=0,invalid=0; }; +TrackerImportResult ParseTrackerImport(const std::string& bytes,const std::wstring& current); +TrackerImportResult ImportTrackerText(const std::wstring& source,bool online,const std::wstring& current,const std::atomic& canceled); diff --git a/client/src/settings/tracker_settings.h b/client/src/settings/tracker_settings.h new file mode 100644 index 0000000..55ea5ca --- /dev/null +++ b/client/src/settings/tracker_settings.h @@ -0,0 +1,59 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#pragma comment(lib,"advapi32.lib") +inline std::wstring DefaultTrackers() { return L"udp://tracker.opentrackr.org:1337/announce\r\nudp://open.stealth.si:80/announce\r\nudp://tracker.torrent.eu.org:451/announce\r\n"; } +inline bool ParseTrackers(const std::wstring& text,std::vector& urls,std::wstring& error) { + urls.clear(); error.clear(); std::set unique; + size_t pos=0,line=0; + while(pos=L'a'&&c<=L'z')||(c>=L'A'&&c<=L'Z')||(c>=L'0'&&c<=L'9')||c==L'-'||c==L'.'||c==L'_'||c==L':'||c==L'['||c==L']'||c==L'%')) return fail(L"主机名含无效字符"); + size_t colon=host.rfind(L':'); + if(host.front()==L'[') { auto close=host.find(L']'); if(close==std::wstring::npos || close<2) return fail(L"IPv6 地址无效"); if(close+1==host.size()) colon=std::wstring::npos; else if(host[close+1]!=L':') return fail(L"端口无效"); } + if(colon!=std::wstring::npos) { + auto port=host.substr(colon+1); unsigned number=0; + if(port.empty() || port.size()>5 || colon==0) return fail(L"端口无效"); + for(auto c:port) { if(cL'9') return fail(L"端口无效"); number=number*10+c-L'0'; } + if(number==0 || number>65535) return fail(L"端口超出范围"); + } else if(start==6) return fail(L"UDP Tracker 必须指定端口"); + if(unique.insert(url).second) urls.push_back(url); + } + return true; +} +inline std::wstring TrackerText(const std::vector& urls) { std::wstring text; for(const auto& url:urls) text+=url+L"\r\n"; return text; } +inline std::wstring LoadTrackers() { + HKEY key=nullptr; if(RegOpenKeyExW(HKEY_CURRENT_USER,L"Software\\TTDownloader",0,KEY_QUERY_VALUE,&key)!=ERROR_SUCCESS) return DefaultTrackers(); + DWORD size=0,type=0; auto status=RegQueryValueExW(key,L"Trackers",nullptr,&type,nullptr,&size); + std::wstring value; + while(status==ERROR_SUCCESS && type==REG_SZ && size>=sizeof(wchar_t) && size%sizeof(wchar_t)==0) { + value.resize(size/sizeof(wchar_t)); + status=RegQueryValueExW(key,L"Trackers",nullptr,&type,reinterpret_cast(value.data()),&size); + if(status==ERROR_MORE_DATA) { status=ERROR_SUCCESS; continue; } + if(status!=ERROR_SUCCESS || type!=REG_SZ || size%sizeof(wchar_t)) { value.clear(); break; } + value.resize(size/sizeof(wchar_t)); + while(!value.empty() && value.back()==L'\0') value.pop_back(); + break; + } + if(status==ERROR_FILE_NOT_FOUND) value=DefaultTrackers(); + RegCloseKey(key); return value; +} +inline bool SaveTrackers(const std::wstring& text) { + // RegSetValueEx represents the byte count as DWORD, including the terminator. + if(text.size()>((std::numeric_limits::max)()/sizeof(wchar_t))-1) return false; + HKEY key=nullptr; if(RegCreateKeyExW(HKEY_CURRENT_USER,L"Software\\TTDownloader",0,nullptr,0,KEY_SET_VALUE,nullptr,&key,nullptr)!=ERROR_SUCCESS) return false; + auto status=RegSetValueExW(key,L"Trackers",0,REG_SZ,reinterpret_cast(text.c_str()),static_cast((text.size()+1)*2)); RegCloseKey(key); return status==ERROR_SUCCESS; +} diff --git a/client/src/task_store.cpp b/client/src/storage/task_store.cpp similarity index 98% rename from client/src/task_store.cpp rename to client/src/storage/task_store.cpp index 6117bd0..59411d9 100644 --- a/client/src/task_store.cpp +++ b/client/src/storage/task_store.cpp @@ -1,6 +1,6 @@ #include "stdafx.h" -#include "platform.h" -#include "task_store.h" +#include "platform/platform.h" +#include "storage/task_store.h" #include "sqlite3.h" namespace diff --git a/client/src/task_store.h b/client/src/storage/task_store.h similarity index 100% rename from client/src/task_store.h rename to client/src/storage/task_store.h diff --git a/client/src/transport/ftp_transport.cpp b/client/src/transport/ftp_transport.cpp new file mode 100644 index 0000000..2eb66fa --- /dev/null +++ b/client/src/transport/ftp_transport.cpp @@ -0,0 +1,177 @@ +#include "stdafx.h" +#include "transport/ftp_transport.h" +#include "platform/platform.h" +#include "settings/proxy_settings.h" +#include +#include +#include +#include +#include +namespace http { +namespace { +struct Runtime { Runtime() { curl_global_init(CURL_GLOBAL_DEFAULT); } ~Runtime() { curl_global_cleanup(); } }; +void Initialize() { static Runtime runtime; } +using Easy=std::unique_ptr; +using Url=std::unique_ptr; +std::string Part(CURLU* url,CURLUPart field) { + char* raw=nullptr; if (curl_url_get(url,field,&raw,0)!=CURLUE_OK) return {}; + std::string result(raw); curl_free(raw); return result; +} +bool ParseFtp(const std::wstring& text,UrlParts& parts) { + Initialize(); + if (text.size()>16384 || text.find_first_of(L"\r\n\t ")!=std::wstring::npos) return false; + Url url(curl_url(),curl_url_cleanup); + if (!url || curl_url_set(url.get(),CURLUPART_URL,platform::ToUtf8(text).c_str(),0)!=CURLUE_OK) return false; + auto scheme=Part(url.get(),CURLUPART_SCHEME); + if (scheme!="ftp" && scheme!="ftps") return false; + parts={}; parts.host=platform::FromUtf8(Part(url.get(),CURLUPART_HOST)); + parts.path=platform::FromUtf8(Part(url.get(),CURLUPART_PATH)); + auto port=Part(url.get(),CURLUPART_PORT); int number=scheme=="ftps"?990:21; + if (!port.empty()) { number=0; for(char c:port) { if(c<'0'||c>'9'||number>6553) return false; number=number*10+c-'0'; } } + if(number<1 || number>65535) return false; + parts.port=static_cast(number); return !parts.host.empty() && parts.path.size()>1 && parts.path.back()!=L'/'; +} +void Configure(CURL* easy,const Request& request,const ProxySettings& proxy) { + curl_easy_setopt(easy,CURLOPT_URL,platform::ToUtf8(request.url).c_str()); + curl_easy_setopt(easy,CURLOPT_PROTOCOLS_STR,"http,https,ftp,ftps"); + curl_easy_setopt(easy,CURLOPT_REDIR_PROTOCOLS_STR,request.url.rfind(L"https://",0)==0?"https":"http,https"); + curl_easy_setopt(easy,CURLOPT_FOLLOWLOCATION,1L); curl_easy_setopt(easy,CURLOPT_MAXREDIRS,8L); + curl_easy_setopt(easy,CURLOPT_CONNECTTIMEOUT_MS,static_cast(request.timeouts.connect_ms)); + curl_easy_setopt(easy,CURLOPT_NOSIGNAL,1L); + curl_easy_setopt(easy,CURLOPT_FAILONERROR,request.url.rfind(L"ftp",0)==0?1L:0L); + if(proxy.type>0) { + auto host=proxy.host; if(host.find(L':')!=std::wstring::npos && host.front()!=L'[') host=L"["+host+L"]"; + curl_easy_setopt(easy,CURLOPT_PROXY,platform::ToUtf8(host).c_str()); + curl_easy_setopt(easy,CURLOPT_PROXYPORT,std::stol(proxy.port)); + if(proxy.type==1 && request.url.rfind(L"ftp",0)==0) curl_easy_setopt(easy,CURLOPT_HTTPPROXYTUNNEL,1L); + curl_easy_setopt(easy,CURLOPT_PROXYTYPE,proxy.type==2?CURLPROXY_SOCKS5_HOSTNAME:CURLPROXY_HTTP); + curl_easy_setopt(easy,CURLOPT_PROXYUSERNAME,platform::ToUtf8(proxy.user).c_str()); + curl_easy_setopt(easy,CURLOPT_PROXYPASSWORD,platform::ToUtf8(proxy.password).c_str()); + curl_easy_setopt(easy,CURLOPT_PROXYAUTH,CURLAUTH_ANY); + curl_easy_setopt(easy,CURLOPT_NOPROXY,""); + } else curl_easy_setopt(easy,CURLOPT_PROXY,""); + if(!request.referrer.empty()) curl_easy_setopt(easy,CURLOPT_REFERER,platform::ToUtf8(request.referrer).c_str()); + if(!request.user_agent.empty()) curl_easy_setopt(easy,CURLOPT_USERAGENT,platform::ToUtf8(request.user_agent).c_str()); + curl_easy_setopt(easy,CURLOPT_FTP_RESPONSE_TIMEOUT,15L); + curl_easy_setopt(easy,CURLOPT_SSL_VERIFYPEER,1L); + curl_easy_setopt(easy,CURLOPT_SSL_VERIFYHOST,2L); +} +class FtpStream final:public ResponseStream { +public: + explicit FtpStream(const Request& request,Response response,const ProxySettings& proxy):easy_(curl_easy_init(),curl_easy_cleanup),headers_(std::move(response)) { + if (!easy_) return; + Configure(easy_.get(),request,proxy); curl_easy_setopt(easy_.get(),CURLOPT_RESUME_FROM_LARGE,static_cast(request.range_offset)); + curl_easy_setopt(easy_.get(),CURLOPT_HEADERFUNCTION,+[](char* data,size_t size,size_t count,void* self) { + auto& stream=*static_cast(self); std::string line(data,size*count); + if(line.rfind("HTTP/",0)==0) stream.headers_.content_range.clear(); + const std::string key="content-range:"; + if(line.size()>=key.size()) { + std::string prefix=line.substr(0,key.size()); for(auto& c:prefix) c=static_cast(tolower(static_cast(c))); + if(prefix==key) { auto value=line.substr(key.size()); while(!value.empty() && (value.back()=='\r'||value.back()=='\n')) value.pop_back(); stream.headers_.content_range=platform::FromUtf8(value); } + } + return size*count; + }); + curl_easy_setopt(easy_.get(),CURLOPT_HEADERDATA,this); + curl_easy_setopt(easy_.get(),CURLOPT_WRITEFUNCTION,&Write); curl_easy_setopt(easy_.get(),CURLOPT_WRITEDATA,this); + multi_=curl_multi_init(); if (multi_) curl_multi_add_handle(multi_,easy_.get()); + timeout_=request.timeouts.receive_ms; + } + ~FtpStream() override { if(multi_) { curl_multi_remove_handle(multi_,easy_.get()); curl_multi_cleanup(multi_); } } + const Response& Headers() const override { return headers_; } + ReadResult Read(std::span output) override { + if (output.empty() || !multi_) return {ReadState::kError,0,L"FTP 读取器初始化失败"}; + auto deadline=std::chrono::steady_clock::now()+std::chrono::milliseconds(timeout_); + while(buffer_.empty() && !done_) { + if (paused_) { paused_=false; curl_easy_pause(easy_.get(),CURLPAUSE_CONT); } + int running=0; + auto code=curl_multi_perform(multi_,&running); + if(code!=CURLM_OK) return {ReadState::kError,0,L"FTP 传输调度失败"}; + int left=0; while(auto* message=curl_multi_info_read(multi_,&left)) if(message->msg==CURLMSG_DONE) { done_=true; result_=message->data.result; } + if (!buffer_.empty() || done_) break; + if (std::chrono::steady_clock::now()>=deadline) return {ReadState::kTimeout,0,L"FTP 读取超时"}; + int events=0; curl_multi_poll(multi_,nullptr,0,100,&events); + } + if(!buffer_.empty()) { + size_t count=std::min(output.size(),buffer_.size()-position_); std::memcpy(output.data(),buffer_.data()+position_,count); position_+=count; + if(position_==buffer_.size()) { buffer_.clear(); position_=0; } + return {ReadState::kData,count,{}}; + } + if(result_!=CURLE_OK) return {ReadState::kError,0,L"FTP: "+platform::FromUtf8(curl_easy_strerror(result_))}; + return {ReadState::kEnd,0,{}}; + } + void ReadHttpHeaders() { + long code=0; curl_off_t length=-1; curl_easy_getinfo(easy_.get(),CURLINFO_RESPONSE_CODE,&code); curl_easy_getinfo(easy_.get(),CURLINFO_CONTENT_LENGTH_DOWNLOAD_T,&length); + headers_.status=static_cast(code); headers_.content_length=length<0?0:length; + } + CURLcode Result() const { return result_; } +private: + static size_t Write(char* data,size_t size,size_t count,void* context) { + auto& self=*static_cast(context); size_t bytes=size*count; + if (!self.buffer_.empty()) { self.paused_=true; return CURL_WRITEFUNC_PAUSE; } + self.buffer_.assign(data,data+bytes); return bytes; + } + Easy easy_; CURLM* multi_=nullptr; Response headers_; std::vector buffer_; + size_t position_=0; bool paused_=false,done_=false; CURLcode result_=CURLE_OK; int timeout_=4000; +}; +class PrefixedStream final:public ResponseStream { + std::unique_ptr stream_; std::vector prefix_; size_t position_=0; +public: + PrefixedStream(std::unique_ptr stream,std::vector prefix):stream_(std::move(stream)),prefix_(std::move(prefix)) {} + const Response& Headers() const override { return stream_->Headers(); } + ReadResult Read(std::span buffer) override { + if (buffer.empty()) return {ReadState::kError,0,L"读取缓冲区不能为空"}; + if (position_Read(buffer); + } +}; +class FtpTransport final:public Transport { +public: + bool ParseUrl(const std::wstring& url,UrlParts& parts) const override { return ParseFtp(url,parts); } + OpenResult Open(const Request& request) override { + UrlParts parts; + if(request.timeouts.connect_ms<=0 || request.timeouts.receive_ms<=0 || request.timeouts.resolve_ms<=0 || request.timeouts.send_ms<=0 || request.range_offset<0 || !ParseUrl(request.url,parts)) return {nullptr,OpenError::kInvalidRequest,L"无效的 FTP 下载地址"}; + auto proxy=CurrentProxy(); std::wstring proxy_error; if(!ValidateProxy(proxy,proxy_error)) return {nullptr,OpenError::kInvalidRequest,proxy_error}; + Easy metadata(curl_easy_init(),curl_easy_cleanup); if(!metadata) return {nullptr,OpenError::kNetwork,L"FTP 初始化失败"}; + Configure(metadata.get(),request,proxy); curl_easy_setopt(metadata.get(),CURLOPT_NOBODY,1L); + curl_easy_setopt(metadata.get(),CURLOPT_WRITEFUNCTION,+[](char*,size_t size,size_t count,void*) { return size*count; }); + curl_easy_setopt(metadata.get(),CURLOPT_TIMEOUT_MS,15000L); + auto code=curl_easy_perform(metadata.get()); + if(code!=CURLE_OK) return {nullptr,code==CURLE_OPERATION_TIMEDOUT?OpenError::kTimeout:OpenError::kNetwork,L"FTP: "+platform::FromUtf8(curl_easy_strerror(code))}; + curl_off_t size=-1; curl_easy_getinfo(metadata.get(),CURLINFO_CONTENT_LENGTH_DOWNLOAD_T,&size); + metadata.reset(); // Release the probe login before opening the data session. + Response response; response.status=request.range_offset?206:200; + response.content_length=size<0?0:std::max(0,size-request.range_offset); + if(request.range_offset) { + if(size>=0 && request.range_offset>size) response.status=416; + response.content_range=L"bytes "+std::to_wstring(request.range_offset)+L"-"+std::to_wstring(size-1)+L"/"+std::to_wstring(size); + } + auto stream=std::make_unique(request,std::move(response),proxy); + if (stream->Headers().status==416) return {std::move(stream),OpenError::kNone,{}}; + std::vector prefix(64*1024); auto first=stream->Read(prefix); + if (first.state==ReadState::kError && request.range_offset>0 + && (stream->Result()==CURLE_BAD_DOWNLOAD_RESUME || stream->Result()==CURLE_RANGE_ERROR || stream->Result()==CURLE_FTP_COULDNT_USE_REST)) { + Request restart=request; restart.range_offset=0; stream.reset(); return Open(restart); + } + if (first.state==ReadState::kTimeout || first.state==ReadState::kError) + return {nullptr,first.state==ReadState::kTimeout?OpenError::kTimeout:OpenError::kNetwork,first.error}; + prefix.resize(first.size); + return {std::make_unique(std::move(stream),std::move(prefix)),OpenError::kNone,{}}; + } +}; +} +OpenResult OpenProxiedHttp(const Request& request) { + Initialize(); std::wstring error; auto proxy=CurrentProxy(); + if(!ValidateProxy(proxy,error)) return {nullptr,OpenError::kInvalidRequest,error}; + if(request.range_offset<0 || request.timeouts.receive_ms<=0 || request.timeouts.connect_ms<=0 || request.timeouts.resolve_ms<=0 || request.timeouts.send_ms<=0) return {nullptr,OpenError::kInvalidRequest,L"无效的请求参数"}; + for(const auto* header:{&request.referrer,&request.user_agent}) { if(header->size()>16384) return {nullptr,OpenError::kInvalidRequest,L"请求头过长"}; for(auto c:*header) if(c<32 || c==127) return {nullptr,OpenError::kInvalidRequest,L"请求头含控制字符"}; } + auto stream=std::make_unique(request,Response{},proxy); std::vector prefix(64*1024); auto first=stream->Read(prefix); stream->ReadHttpHeaders(); + if(request.range_offset>0 && stream->Result()==CURLE_RANGE_ERROR && stream->Headers().status==200) { Request restart=request; restart.range_offset=0; stream.reset(); return OpenProxiedHttp(restart); } + if(first.state==ReadState::kTimeout || (first.state==ReadState::kError && stream->Headers().status==0)) return {nullptr,first.state==ReadState::kTimeout?OpenError::kTimeout:OpenError::kNetwork,first.error}; + if(first.state==ReadState::kError && stream->Headers().status<400) return {nullptr,OpenError::kNetwork,L"代理 HTTP 传输失败"}; + prefix.resize(first.size); return {std::make_unique(std::move(stream),std::move(prefix)),OpenError::kNone,{}}; +} +std::unique_ptr CreateFtpTransport() { Initialize(); return std::make_unique(); } +} diff --git a/client/src/transport/ftp_transport.h b/client/src/transport/ftp_transport.h new file mode 100644 index 0000000..30b821c --- /dev/null +++ b/client/src/transport/ftp_transport.h @@ -0,0 +1,3 @@ +#pragma once +#include "transport/http_transport.h" +namespace http { std::unique_ptr CreateFtpTransport(); OpenResult OpenProxiedHttp(const Request&); } diff --git a/client/src/transport/http_transport.cpp b/client/src/transport/http_transport.cpp new file mode 100644 index 0000000..cd9fab7 --- /dev/null +++ b/client/src/transport/http_transport.cpp @@ -0,0 +1,17 @@ +#include "stdafx.h" +#include "transport/http_transport.h" +#include "transport/winhttp_transport.h" +#include "transport/ftp_transport.h" +#include "settings/proxy_settings.h" +namespace http { +class DefaultTransport final:public Transport { + std::unique_ptr web_=CreateWinHttpTransport(), ftp_=CreateFtpTransport(); +public: + bool ParseUrl(const std::wstring& url,UrlParts& parts) const override { return web_->ParseUrl(url,parts)||ftp_->ParseUrl(url,parts); } + OpenResult Open(const Request& request) override { + if(CurrentProxy().type!=0) { UrlParts check; if(web_->ParseUrl(request.url,check)) return OpenProxiedHttp(request); } + UrlParts parts; return ftp_->ParseUrl(request.url,parts)?ftp_->Open(request):web_->Open(request); + } +}; +std::unique_ptr CreateDefaultTransport() { return std::make_unique(); } +} diff --git a/client/src/http_transport.h b/client/src/transport/http_transport.h similarity index 100% rename from client/src/http_transport.h rename to client/src/transport/http_transport.h diff --git a/client/src/winhttp_transport.cpp b/client/src/transport/winhttp_transport.cpp similarity index 98% rename from client/src/winhttp_transport.cpp rename to client/src/transport/winhttp_transport.cpp index 307b289..ffe07fa 100644 --- a/client/src/winhttp_transport.cpp +++ b/client/src/transport/winhttp_transport.cpp @@ -1,5 +1,5 @@ #include "stdafx.h" -#include "winhttp_transport.h" +#include "transport/winhttp_transport.h" #include #include #include @@ -133,7 +133,7 @@ public: 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(input.user_agent.empty()?L"TTDownloader/0.1":input.user_agent.c_str(),WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + Handle session(WinHttpOpen(input.user_agent.empty()?L"TTDownloader/0.1":input.user_agent.c_str(),WINHTTP_ACCESS_TYPE_NO_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(input.user_agent.empty()?L"TTDownloader/0.1":input.user_agent.c_str(),WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, diff --git a/client/src/winhttp_transport.h b/client/src/transport/winhttp_transport.h similarity index 69% rename from client/src/winhttp_transport.h rename to client/src/transport/winhttp_transport.h index f55f4e1..2d71729 100644 --- a/client/src/winhttp_transport.h +++ b/client/src/transport/winhttp_transport.h @@ -1,5 +1,5 @@ #pragma once -#include "http_transport.h" +#include "transport/http_transport.h" namespace http { std::unique_ptr CreateWinHttpTransport(); } diff --git a/client/src/add_task_form.cpp b/client/src/ui/add_task_form.cpp similarity index 97% rename from client/src/add_task_form.cpp rename to client/src/ui/add_task_form.cpp index d98249f..8d75ec8 100644 --- a/client/src/add_task_form.cpp +++ b/client/src/ui/add_task_form.cpp @@ -1,5 +1,5 @@ #include "stdafx.h" -#include "add_task_form.h" +#include "ui/add_task_form.h" #include #include #include @@ -26,7 +26,7 @@ AddTaskForm::AddTaskForm(SkinSettings* skin,SubmitCallback submit) :skin_(skin),submit_(std::move(submit)),directory_(DefaultDirectory()) { SetOpacity(skin_->window_alpha_percent); } AddTaskForm::~AddTaskForm() { if (IsOpen()) DestroyWindow(GetHWND()); } void AddTaskForm::OnCreate() { - edit_url_=CreateEdit(kUrl,L"粘贴一个 HTTP/HTTPS 下载地址"); + edit_url_=CreateEdit(kUrl,L"粘贴 HTTP/HTTPS、FTP 或 magnet 下载地址"); edit_path_=CreateEdit(kPath,L"下载保存目录"); SetWindowTextW(edit_url_,url_.c_str()); SetWindowTextW(edit_path_,directory_.c_str()); SendMessageW(edit_url_,EM_SETREADONLY,url_read_only_,0); diff --git a/client/src/add_task_form.h b/client/src/ui/add_task_form.h similarity index 96% rename from client/src/add_task_form.h rename to client/src/ui/add_task_form.h index f07c34b..84b3192 100644 --- a/client/src/add_task_form.h +++ b/client/src/ui/add_task_form.h @@ -1,6 +1,6 @@ #pragma once #include "ttui/window.h" -#include "skin_settings.h" +#include "settings/skin_settings.h" #include class AddTaskForm final : public ttui::Window { public: diff --git a/client/src/downloader_form.cpp b/client/src/ui/downloader_form.cpp similarity index 91% rename from client/src/downloader_form.cpp rename to client/src/ui/downloader_form.cpp index 7a1dab3..ef89c17 100644 --- a/client/src/downloader_form.cpp +++ b/client/src/ui/downloader_form.cpp @@ -1,9 +1,11 @@ #include "stdafx.h" -#include "downloader_form.h" -#include "file_drop_source.h" -#include "settings_form.h" -#include "add_task_form.h" -#include "client_browser_bridge.h" +#include "ui/downloader_form.h" +#include "integration/file_drop_source.h" +#include "ui/settings_form.h" +#include "ui/tracker_form.h" +#include "ui/proxy_form.h" +#include "ui/add_task_form.h" +#include "integration/client_browser_bridge.h" #include #include @@ -100,6 +102,7 @@ namespace switch (info.state) { case TaskState::kDownloading: + if (IsMagnet(info.url) && info.total_bytes==0) return L"获取元数据 · "+info.error; if (info.total_bytes > 0) { int percent = static_cast(info.downloaded_bytes * 100 / info.total_bytes); @@ -134,12 +137,14 @@ namespace const std::wstring DownloaderForm::kClassName=L"TTDownloaderMainWindow"; -namespace { enum { kAdd=200,kStart,kPause,kDelete,kSettings,kExit,kDownloading,kCompleted,kDeleted,kScheduled }; } +namespace { enum { kAdd=200,kStart,kPause,kDelete,kSettings,kExit,kDownloading,kCompleted,kDeleted,kScheduled,kTrackers,kProxy }; } DownloaderForm::DownloaderForm():taskbar_created_message_(RegisterWindowMessageW(L"TaskbarCreated")) { LoadSkinSettings(); SetOpacity(skin_.window_alpha_percent); } DownloaderForm::~DownloaderForm() { + if (proxy_form_) proxy_form_->Close(); + if (tracker_form_) tracker_form_->Close(); if (settings_form_) settings_form_->Close(); if (add_task_form_) add_task_form_->Close(); if (IsOpen()) DestroyWindow(GetHWND()); @@ -156,6 +161,8 @@ void DownloaderForm::OnCreate() { AppendMenuW(file_menu,MF_SEPARATOR,0,nullptr); AppendMenuW(file_menu,MF_STRING,kExit,L"退出(&X)"); AppendMenuW(settings_menu,MF_STRING,kSettings,L"外观设置(&O)..."); + AppendMenuW(settings_menu,MF_STRING,kTrackers,L"Tracker 设置(&T)..."); + AppendMenuW(settings_menu,MF_STRING,kProxy,L"代理设置(&P)..."); AppendMenuW(menu_bar,MF_POPUP,reinterpret_cast(file_menu),L"文件(&F)"); AppendMenuW(menu_bar,MF_POPUP,reinterpret_cast(settings_menu),L"设置(&S)"); SetMenu(GetHWND(),menu_bar); @@ -240,6 +247,8 @@ void DownloaderForm::OnCommand(int id) { case kPause: PauseSelectedTask(); break; case kDelete: DeleteSelectedTask(); break; case kSettings: ShowSettingsForm(); break; + case kTrackers: ShowTrackerForm(); break; + case kProxy: ShowProxyForm(); break; case kExit: Close(); break; } } @@ -250,6 +259,14 @@ void DownloaderForm::UpdateViewport() { SetScrollInfo(Page().scrollbar,SB_CTL,&info,TRUE); Invalidate(); } std::optional DownloaderForm::OnMessage(UINT msg,WPARAM wp,LPARAM lp) { + if (msg==WM_GETMINMAXINFO) { + RECT outer{},client{}; GetWindowRect(GetHWND(),&outer); GetClientRect(GetHWND(),&client); + auto* limits=reinterpret_cast(lp); + limits->ptMinTrackSize.x=static_cast(760*Scale())+std::max(0,(outer.right-outer.left)-(client.right-client.left)); + limits->ptMinTrackSize.y=static_cast(420*Scale())+std::max(0,(outer.bottom-outer.top)-(client.bottom-client.top)); + return 0; + } + if (msg==WM_COPYDATA) { auto request=std::make_unique(); if (!DecodeStartupCopyData(reinterpret_cast(lp),*request)) return FALSE; @@ -281,13 +298,17 @@ std::optional DownloaderForm::OnMessage(UINT msg,WPARAM wp,LPARAM lp) { SyncPages(); UpdateSummary(); UpdateSelectedInfo(); Invalidate(); return 0; } if (msg==WM_SYSCOMMAND && (wp&0xfff0)==SC_MINIMIZE) { - ShowWindow(SW_HIDE); if (settings_form_) settings_form_->ShowWindow(SW_HIDE); + ShowWindow(SW_HIDE); if(proxy_form_) proxy_form_->ShowWindow(SW_HIDE); if (tracker_form_) tracker_form_->ShowWindow(SW_HIDE); if (settings_form_) settings_form_->ShowWindow(SW_HIDE); if (add_task_form_) add_task_form_->ShowWindow(SW_HIDE); return 0; } + if(msg==WM_SHOWWINDOW && wp && proxy_form_ && proxy_form_->IsOpen()) proxy_form_->ShowWindow(SW_SHOWNOACTIVATE); + if (msg==WM_SHOWWINDOW && wp && tracker_form_ && tracker_form_->IsOpen()) tracker_form_->ShowWindow(SW_SHOWNOACTIVATE); if (msg==WM_SHOWWINDOW && wp && settings_form_ && settings_form_->IsOpen()) settings_form_->ShowWindow(SW_SHOWNOACTIVATE); if (msg==WM_SHOWWINDOW && wp && add_task_form_ && add_task_form_->IsOpen()) add_task_form_->ShowWindow(SW_SHOWNOACTIVATE); if (msg==WM_DESTROY) { if (add_task_form_) add_task_form_->Close(); + if (proxy_form_) proxy_form_->Close(); + if (tracker_form_) tracker_form_->Close(); if (settings_form_) settings_form_->Close(); StopEngine(); RemoveTrayIcon(); } if (msg==WM_VSCROLL && reinterpret_cast(lp)==Page().scrollbar) { @@ -510,9 +531,23 @@ void DownloaderForm::ShowSettingsForm() { if (!settings_form_->Create(GetHWND(),SettingsForm::kClassName.c_str(),L"外观设置",600,228)) { settings_form_.reset(); return; } settings_form_->CenterWindow(); settings_form_->ShowWindow(); } +void DownloaderForm::ShowProxyForm() { + if(proxy_form_ && proxy_form_->IsOpen()) { proxy_form_->ActiveWindow(); return; } + proxy_form_=std::make_unique(&skin_,[this] { if(engine_) engine_->RefreshProxy(); }); + if(!proxy_form_->Create(GetHWND(),ProxyForm::kClassName.c_str(),L"代理设置",620,380)) { proxy_form_.reset(); return; } + proxy_form_->CenterWindow(); proxy_form_->ShowWindow(); +} +void DownloaderForm::ShowTrackerForm() { + if (tracker_form_ && tracker_form_->IsOpen()) { tracker_form_->ActiveWindow(); return; } + tracker_form_=std::make_unique(&skin_,[this](const auto& urls) { if(engine_) engine_->ConfigureTrackers(urls); }); + if (!tracker_form_->Create(GetHWND(),TrackerForm::kClassName.c_str(),L"Tracker 设置",680,480)) { tracker_form_.reset(); return; } + tracker_form_->CenterWindow(); tracker_form_->ShowWindow(); +} void DownloaderForm::ApplySkinSettings() { SetOpacity(skin_.window_alpha_percent); if (settings_form_) settings_form_->RefreshOpacity(); + if (tracker_form_) tracker_form_->RefreshAppearance(); + if(proxy_form_) proxy_form_->RefreshAppearance(); SetBackgroundImage(skin_.background_image); SetBackgroundImageOpacity(1-skin_.window_opacity/100.f); Invalidate(); if (add_task_form_) { add_task_form_->RefreshAppearance(); add_task_form_->Preview(); } } @@ -663,6 +698,12 @@ void DownloaderForm::DeleteSelectedTask() return; const int64_t task_id = Rows()[index].info.id; + if (IsMagnet(Rows()[index].info.url)) { + if (MessageBoxW(GetHWND(),L"删除磁力任务记录?已下载文件和恢复数据将保留。",L"删除任务",MB_OKCANCEL|MB_ICONQUESTION)==IDOK) + engine_->DeleteTask(task_id,false); + return; + } + int result = ::MessageBoxW(GetHWND(), L"确定删除选中的任务吗?\n\n" L"是:同时删除已下载的文件\n" diff --git a/client/src/downloader_form.h b/client/src/ui/downloader_form.h similarity index 90% rename from client/src/downloader_form.h rename to client/src/ui/downloader_form.h index e282000..7a823e1 100644 --- a/client/src/downloader_form.h +++ b/client/src/ui/downloader_form.h @@ -1,14 +1,16 @@ #pragma once #include "ttui/window.h" #include "ttui/virtual_list.h" -#include "download_engine.h" -#include "skin_settings.h" -#include "client_browser_bridge.h" -#include "startup_options.h" +#include "engine/download_engine.h" +#include "settings/skin_settings.h" +#include "integration/client_browser_bridge.h" +#include "app/startup_options.h" #include #include #include class SettingsForm; +class TrackerForm; +class ProxyForm; class AddTaskForm; namespace browser_bridge { class PipeServer; } class DownloaderForm final : public ttui::Window { @@ -46,6 +48,8 @@ private: void RemoveTrayIcon(); void ShowTrayMenu(); void ShowSettingsForm(); + void ShowTrackerForm(); + void ShowProxyForm(); void ApplySkinSettings(); void LoadSkinSettings(); void SaveSkinSettings(); @@ -68,6 +72,8 @@ private: SkinSettings skin_; std::unique_ptr settings_form_; + std::unique_ptr tracker_form_; + std::unique_ptr proxy_form_; std::unique_ptr add_task_form_; struct BrowserDraft { ExternalDownload download; diff --git a/client/src/ui/proxy_form.cpp b/client/src/ui/proxy_form.cpp new file mode 100644 index 0000000..319fd8b --- /dev/null +++ b/client/src/ui/proxy_form.cpp @@ -0,0 +1,33 @@ +#include "stdafx.h" +#include "ui/proxy_form.h" +const std::wstring ProxyForm::kClassName=L"TTDownloaderProxySettings"; +ProxyForm::ProxyForm(SkinSettings* skin,std::function applied):skin_(skin),settings_(CurrentProxy()),applied_(std::move(applied)) { if(settings_.type<0) { status_=L"代理配置无法解密,请重新保存。"; settings_.type=0; } RefreshAppearance(); } +ProxyForm::~ProxyForm() { if(IsOpen()) DestroyWindow(GetHWND()); } +void ProxyForm::RefreshAppearance() { SetOpacity(skin_->window_alpha_percent); SetBackgroundImage(skin_->background_image); SetBackgroundImageOpacity(1-skin_->window_opacity/100.f); Invalidate(); } +void ProxyForm::OnCreate() { + host_=CreateEdit(100,L"127.0.0.1 或代理主机名"); port_=CreateEdit(101,L"端口"); user_=CreateEdit(102,L"可选用户名"); password_=CreateEdit(103,L"可选密码"); + SendMessageW(password_,EM_SETPASSWORDCHAR,0x25cf,0); + SetWindowTextW(host_,settings_.host.c_str()); SetWindowTextW(port_,settings_.port.c_str()); SetWindowTextW(user_,settings_.user.c_str()); SetWindowTextW(password_,settings_.password.c_str()); +} +void ProxyForm::OnLayout() { + ClearButtons(); Button(10,L"直连",{24,20,140,54},settings_.type==0); Button(11,L"HTTP",{152,20,268,54},settings_.type==1); Button(12,L"SOCKS5",{280,20,396,54},settings_.type==2); + Place(host_,{104,76,Width()-140,110}); Place(port_,{Width()-128,76,Width()-24,110}); Place(user_,{104,126,Width()-24,160}); Place(password_,{104,176,Width()-24,210}); + for(auto field:{host_,port_,user_,password_}) EnableWindow(field,settings_.type!=0); + Button(1,L"保存并应用",{Width()-270,Height()-52,Width()-140,Height()-18},true); Button(2,L"关闭",{Width()-124,Height()-52,Width()-24,Height()-18}); +} +void ProxyForm::OnPaint(ttui::Canvas& c) { + c.Text(L"代理地址",{24,76,100,110}); c.Text(L"用户名",{24,126,100,160}); c.Text(L"密码",{24,176,100,210}); + c.Text(L"HTTP 代理不支持 UDP Tracker / DHT;SOCKS5 需服务端支持 UDP。",{24,226,Width()-24,254},0x64748B,12); + c.Text(status_,{24,258,Width()-24,Height()-64},0x64748B,13); +} +void ProxyForm::OnCommand(int id) { + if(id>=10 && id<=12) { settings_.type=id-10; OnLayout(); Preview(); } + if(id==2) Close(); + if(id==1) { + settings_.host=EditText(host_); settings_.port=EditText(port_); settings_.user=EditText(user_); settings_.password=EditText(password_); + if(!ValidateProxy(settings_,status_)) { Preview(); return; } + if(!SaveProxy(settings_)) { status_=L"保存或密码加密失败,配置未应用。"; Preview(); return; } + SetCurrentProxy(settings_); if(applied_) applied_(); + status_=L"已保存。磁力将重建连接;现有 HTTP/FTP 下载请暂停后继续。"; Preview(); + } +} diff --git a/client/src/ui/proxy_form.h b/client/src/ui/proxy_form.h new file mode 100644 index 0000000..b6eb9d5 --- /dev/null +++ b/client/src/ui/proxy_form.h @@ -0,0 +1,20 @@ +#pragma once +#include "ttui/window.h" +#include "settings/skin_settings.h" +#include "settings/proxy_settings.h" +#include +class ProxyForm final:public ttui::Window { +public: + ProxyForm(SkinSettings*,std::function); + ~ProxyForm() override; + static const std::wstring kClassName; + void RefreshAppearance(); +private: + void OnCreate() override; + void OnLayout() override; + void OnPaint(ttui::Canvas&) override; + void OnCommand(int) override; + SkinSettings* skin_; ProxySettings settings_; std::function applied_; + HWND host_=nullptr,port_=nullptr,user_=nullptr,password_=nullptr; + std::wstring status_; +}; diff --git a/client/src/settings_form.cpp b/client/src/ui/settings_form.cpp similarity index 99% rename from client/src/settings_form.cpp rename to client/src/ui/settings_form.cpp index ac89c1f..ff5c54a 100644 --- a/client/src/settings_form.cpp +++ b/client/src/ui/settings_form.cpp @@ -1,5 +1,5 @@ #include "stdafx.h" -#include "settings_form.h" +#include "ui/settings_form.h" #include #include #include diff --git a/client/src/settings_form.h b/client/src/ui/settings_form.h similarity index 95% rename from client/src/settings_form.h rename to client/src/ui/settings_form.h index 479d008..3c60d48 100644 --- a/client/src/settings_form.h +++ b/client/src/ui/settings_form.h @@ -1,6 +1,6 @@ #pragma once #include "ttui/window.h" -#include "skin_settings.h" +#include "settings/skin_settings.h" #include class SettingsForm final : public ttui::Window { public: diff --git a/client/src/ui/tracker_form.cpp b/client/src/ui/tracker_form.cpp new file mode 100644 index 0000000..57e4b6c --- /dev/null +++ b/client/src/ui/tracker_form.cpp @@ -0,0 +1,74 @@ +#include "stdafx.h" +#include "ui/tracker_form.h" +#include "settings/tracker_settings.h" +#include +#include +#include +#pragma comment(lib,"comdlg32.lib") +const std::wstring TrackerForm::kClassName=L"TTDownloaderTrackerSettings"; +TrackerForm::TrackerForm(SkinSettings* skin,std::function&)> applied):skin_(skin),applied_(std::move(applied)) { RefreshAppearance(); } +TrackerForm::~TrackerForm() { if(job_) job_->canceled=true; if(IsOpen()) DestroyWindow(GetHWND()); } +void TrackerForm::RefreshAppearance() { SetOpacity(skin_->window_alpha_percent); SetBackgroundImage(skin_->background_image); SetBackgroundImageOpacity(1-skin_->window_opacity/100.f); Invalidate(); } +void TrackerForm::OnCreate() { edit_=CreateEdit(100,L"每行一个 UDP / HTTP / HTTPS Tracker",true); SendMessageW(edit_,EM_SETLIMITTEXT,(std::numeric_limits::max)()-1,0); SetWindowTextW(edit_,LoadTrackers().c_str()); source_=CreateEdit(101,L"HTTP/HTTPS TXT 在线地址"); } +void TrackerForm::OnLayout() { + Place(source_,{24,68,Width()-244,102}); + Place(edit_,{24,114,Width()-24,Height()-116}); ClearButtons(); + Button(4,L"在线导入",{Width()-232,68,Width()-132,102}); Button(5,L"本地导入",{Width()-124,68,Width()-24,102}); + Button(1,L"保存并应用",{Width()-270,Height()-52,Width()-140,Height()-18},true); + Button(2,L"默认列表",{24,Height()-52,140,Height()-18}); Button(3,L"关闭",{Width()-124,Height()-52,Width()-24,Height()-18}); +} +void TrackerForm::OnPaint(ttui::Canvas& c) { + c.Text(L"每行一个 Tracker;保存后立即补充到当前磁力任务。",{24,16,Width()-24,42},0x64748B,13); + c.Text(L"支持 UDP / HTTP / HTTPS Tracker,HTTPS 使用证书验证。",{24,38,Width()-24,62},0x64748B,12); + c.Text(status_,{24,Height()-108,Width()-24,Height()-60},0x64748B,13); +} +void TrackerForm::OnCommand(int id) { + if(id==3) { Close(); return; } + if(job_) { status_=L"正在导入,请稍候;可以关闭窗口取消。"; Preview(); return; } + if(id==4 || id==5) { StartImport(id==4); return; } + if(id==2) { SetWindowTextW(edit_,DefaultTrackers().c_str()); status_=L"已填入默认列表,点击保存后生效。"; Preview(); } + if(id==1) { + std::vector urls; + if(!ParseTrackers(EditText(edit_),urls,status_)) { Preview(); return; } + auto text=TrackerText(urls); + if(!SaveTrackers(text)) { status_=L"保存失败,请检查当前用户配置权限、系统容量或可用内存。"; Preview(); return; } + SetWindowTextW(edit_,text.c_str()); if(applied_) applied_(urls); + status_=L"已保存 "+std::to_wstring(urls.size())+L" 个 Tracker,正在重新寻找节点;无资源节点时仍可能等待。"; Preview(); + } +} + +void TrackerForm::StartImport(bool online) { + std::wstring source=EditText(source_); + if(!online) { + wchar_t path[32768]{}; OPENFILENAMEW dialog{sizeof(dialog)}; + dialog.hwndOwner=GetHWND(); dialog.lpstrFilter=L"TXT 文件\0*.txt\0所有文件\0*.*\0"; + dialog.lpstrFile=path; dialog.nMaxFile=32768; dialog.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR; + if(!GetOpenFileNameW(&dialog)) return; source=path; + } + if(source.empty()) { status_=L"请输入 TXT 在线地址"; Preview(); return; } + auto current=EditText(edit_); auto job=std::make_shared(); + job_=job; EnableWindow(edit_,FALSE); EnableWindow(source_,FALSE); + status_=L"正在读取 TXT,导入后需点击保存才生效。"; Preview(); + if(!SetTimer(GetHWND(),1,100,nullptr)) { job_.reset(); EnableWindow(edit_,TRUE); EnableWindow(source_,TRUE); status_=L"无法启动导入"; Preview(); return; } + try { + std::thread([job,source,online,current] { + try { job->result=ImportTrackerText(source,online,current,job->canceled); } + catch(...) { job->result.error=L"导入失败,原列表保持不变。"; } + job->done=true; + }).detach(); + } catch(...) { KillTimer(GetHWND(),1); job_.reset(); EnableWindow(edit_,TRUE); EnableWindow(source_,TRUE); status_=L"无法启动导入线程"; Preview(); } +} +std::optional TrackerForm::OnMessage(UINT msg,WPARAM wp,LPARAM) { + if(msg==WM_TIMER && wp==1 && job_ && job_->done) { + auto result=std::move(job_->result); job_.reset(); KillTimer(GetHWND(),1); + EnableWindow(edit_,TRUE); EnableWindow(source_,TRUE); + if(!result.error.empty()) status_=result.error; + else { + SetWindowTextW(edit_,result.text.c_str()); + status_=L"新增 "+std::to_wstring(result.added)+L",重复 "+std::to_wstring(result.duplicates)+L",无效 "+std::to_wstring(result.invalid)+L"。请保存后应用。"; + } + Preview(); return 0; + } + if(msg==WM_DESTROY) { KillTimer(GetHWND(),1); if(job_) job_->canceled=true; job_.reset(); edit_=source_=nullptr; } + return {}; +} diff --git a/client/src/ui/tracker_form.h b/client/src/ui/tracker_form.h new file mode 100644 index 0000000..e4fdae7 --- /dev/null +++ b/client/src/ui/tracker_form.h @@ -0,0 +1,26 @@ +#pragma once +#include "ttui/window.h" +#include "settings/skin_settings.h" +#include +#include +#include +#include "settings/tracker_import.h" +class TrackerForm final:public ttui::Window { +public: + TrackerForm(SkinSettings*,std::function&)>); + ~TrackerForm() override; + void RefreshAppearance(); + static const std::wstring kClassName; +private: + void OnCreate() override; + void OnLayout() override; + void OnPaint(ttui::Canvas&) override; + void OnCommand(int) override; + std::optional OnMessage(UINT,WPARAM,LPARAM) override; + void StartImport(bool); + struct ImportJob { std::atomic canceled=false,done=false; TrackerImportResult result; }; + std::shared_ptr job_; + HWND source_=nullptr; + SkinSettings* skin_; HWND edit_=nullptr; std::wstring status_; + std::function&)> applied_; +}; diff --git a/client/tests/http_transport_tests.cpp b/client/tests/http_transport_tests.cpp index 009bd5b..a521a29 100644 --- a/client/tests/http_transport_tests.cpp +++ b/client/tests/http_transport_tests.cpp @@ -1,4 +1,5 @@ -#include "http_transport.h" +#include "settings/proxy_settings.h" +#include "transport/http_transport.h" #include #include #include @@ -22,7 +23,7 @@ static void Run(const std::wstring& base) { http::UrlParts parts; Check(transport->ParseUrl(L"https://example.test:8443/path?x=1",parts) && parts.https && parts.port==8443 && parts.host==L"example.test" && parts.path==L"/path?x=1","backend URL parsing"); - Check(!transport->ParseUrl(L"ftp://example.test/file",parts),"reject unsupported scheme"); + Check(!transport->ParseUrl(L"sftp://example.test/file",parts),"reject unsupported scheme"); std::vector payload; for (int i=0;i<256*257;++i) payload.push_back(static_cast(i%256)); const std::string tail="TTDownloader-http"; payload.insert(payload.end(),tail.begin(),tail.end()); @@ -83,7 +84,7 @@ static void Run(const std::wstring& base) { 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"; + http::Request invalid; invalid.url=L"sftp://example.test/file"; Check(transport->Open(invalid).kind==http::OpenError::kInvalidRequest,"invalid URL classification"); invalid.url=base+L"/plain"; invalid.range_offset=-1; Check(transport->Open(invalid).kind==http::OpenError::kInvalidRequest,"negative range offset classification"); @@ -93,6 +94,7 @@ static void Run(const std::wstring& base) { int wmain(int argc,wchar_t** argv) { if (argc!=2) { std::cerr<<"Expected loopback server URL\n"; return 2; } try { + SetCurrentProxy({}); // All transport I/O runs on a worker, without UI, user tasks or SQLite. std::async(std::launch::async,Run,std::wstring(argv[1])).get(); std::cout<<"PASS: HTTP full/range/ignored range, status errors, redirects, chunked data, 64-bit length, timeout and stream lifetime\n"; diff --git a/client/tests/http_transport_tests.vcxproj b/client/tests/http_transport_tests.vcxproj index e836afd..42a2287 100644 --- a/client/tests/http_transport_tests.vcxproj +++ b/client/tests/http_transport_tests.vcxproj @@ -21,8 +21,10 @@ - - + + + + diff --git a/client/tests/protocol_tests.cpp b/client/tests/protocol_tests.cpp new file mode 100644 index 0000000..1a13897 --- /dev/null +++ b/client/tests/protocol_tests.cpp @@ -0,0 +1,185 @@ +#include "settings/proxy_settings.h" +#include "platform/platform.h" +#include "transport/http_transport.h" +#include "engine/torrent_backend.h" +#include "engine/download_link.h" +#include "settings/tracker_settings.h" +#include "settings/tracker_import.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace lt=libtorrent; +void Check(bool ok,const char* text) { if(!ok) throw std::runtime_error(text); } +std::string Drain(http::ResponseStream& stream) { + std::string result; char buffer[7919]; + for(;;) { auto read=stream.Read(buffer); if(read.state==http::ReadState::kEnd) return result; + Check(read.state==http::ReadState::kData,"FTP stream read"); result.append(buffer,read.size); } +} +void Certificate(const std::filesystem::path& root) { + std::filesystem::create_directories(root); + auto* context=EVP_PKEY_CTX_new_id(EVP_PKEY_RSA,nullptr); Check(context!=nullptr,"create test key"); + EVP_PKEY* key=nullptr; Check(EVP_PKEY_keygen_init(context)>0 && EVP_PKEY_CTX_set_rsa_keygen_bits(context,2048)>0 && EVP_PKEY_keygen(context,&key)>0,"generate local test key"); + auto* certificate=X509_new(); X509_set_version(certificate,2); ASN1_INTEGER_set(X509_get_serialNumber(certificate),1); + X509_gmtime_adj(X509_getm_notBefore(certificate),-60); X509_gmtime_adj(X509_getm_notAfter(certificate),86400); X509_set_pubkey(certificate,key); + auto* name=X509_get_subject_name(certificate); X509_NAME_add_entry_by_txt(name,"CN",MBSTRING_ASC,reinterpret_cast("localhost"),-1,-1,0); X509_set_issuer_name(certificate,name); + X509V3_CTX extension{}; X509V3_set_ctx(&extension,certificate,certificate,nullptr,nullptr,0); + auto* san=X509V3_EXT_conf_nid(nullptr,&extension,NID_subject_alt_name,const_cast("DNS:localhost,IP:127.0.0.1")); X509_add_ext(certificate,san,-1); X509_EXTENSION_free(san); + Check(X509_sign(certificate,key,EVP_sha256())>0,"sign untrusted test certificate"); + FILE* file=nullptr; _wfopen_s(&file,(root/L"cert.pem").c_str(),L"wb"); Check(file && PEM_write_X509(file,certificate),"write test certificate"); fclose(file); + _wfopen_s(&file,(root/L"key.pem").c_str(),L"wb"); Check(file && PEM_write_PrivateKey(file,key,nullptr,nullptr,0,nullptr,nullptr),"write test key"); fclose(file); + X509_free(certificate); EVP_PKEY_free(key); EVP_PKEY_CTX_free(context); +} +int wmain(int argc,wchar_t** argv) { + try { + SetCurrentProxy({}); + if(argc==3 && std::wstring(argv[1])==L"--tls-fixture") { Certificate(argv[2]); return 0; } + const bool import_only=argc==3 && std::wstring(argv[1])==L"--tracker-import-tests"; + Check(argc==6 || import_only,"loopback fixture URL required"); const std::wstring base=argv[1]; + auto imported=ParseTrackerImport("\xef\xbb\xbfudp://127.0.0.1:1234/announce\r\nhttp://127.0.0.1:8080/announce\nhttps://unsupported.test/a\n",L"udp://127.0.0.1:1234/announce"); + Check(imported.error.empty() && imported.added==2 && imported.duplicates==1 && imported.skipped==0,"TXT import merges, deduplicates and reports unsupported entries"); + auto https_only=ParseTrackerImport("https://tracker.example/announce\n",L""); + Check(https_only.added==1 && https_only.skipped==0 && https_only.error.empty(),"HTTPS tracker TXT import is supported"); + std::wstring full_list; + for(int i=0;i<2000;++i) full_list+=L"http://tracker.example/"+std::to_wstring(i)+L"\n"; + auto appended=ParseTrackerImport("https://tracker.example/announce\ninvalid\n",full_list); + Check(appended.added==1 && appended.invalid==1 && appended.skipped==1,"append beyond former 128 tracker and 32767 character caps"); + std::vector many; std::wstring parse_error; + Check(ParseTrackers(appended.text,many,parse_error) && many.size()==2001,"large tracker list remains complete after normalization"); + auto long_url=ParseTrackerImport("https://tracker.example/"+std::string(3000,'a')+"\n",L""); + Check(long_url.added==1 && long_url.error.empty(),"do not impose an arbitrary tracker URL length cap"); + Check(!ParseTrackerImport("bad gateway",L"").error.empty(),"reject HTML as tracker list"); + std::string large_text; + for(int i=0;i<6000;++i) large_text+="https://tracker.example/"+std::to_string(i)+"/"+std::string(180,'a')+"\n"; + auto large=ParseTrackerImport(large_text,L""); + Check(large_text.size()>1024*1024 && large.added==6000 && large.error.empty(),"import valid TXT above former 1 MiB limit without truncation"); + std::atomic canceled=false; + auto txt_base=std::wstring(argv[2]); + for(auto route:{L"/trackers.txt",L"/redirect.txt"}) { + auto remote=ImportTrackerText(txt_base+route,true,L"",canceled); + Check(remote.error.empty() && remote.added==3 && remote.duplicates==1 && remote.skipped==0,"online TXT import and redirect use loopback only"); + } + Check(!ImportTrackerText(txt_base+L"/missing.txt",true,L"",canceled).error.empty(),"online TXT 404 must not replace current list"); + auto remote_large=ImportTrackerText(txt_base+L"/large.txt",true,L"",canceled); + Check(remote_large.added==6000 && remote_large.error.empty(),"online TXT above 1 MiB is imported in full"); + auto txt_path=std::filesystem::temp_directory_path()/(L"TTDownloader_tracker_import_"+std::to_wstring(GetCurrentProcessId())+L".txt"); + const std::wstring wide_txt=L"udp://127.0.0.1:1234/announce\r\n"; + { std::ofstream out(txt_path,std::ios::binary); out.put(char(255)); out.put(char(254)); out.write(reinterpret_cast(wide_txt.data()),wide_txt.size()*2); } + auto local=ImportTrackerText(txt_path.wstring(),false,L"",canceled); + Check(local.error.empty() && local.added==1,"local UTF-16 TXT import"); + { std::ofstream out(txt_path,std::ios::binary|std::ios::trunc); out.write(large_text.data(),large_text.size()); } + auto local_large=ImportTrackerText(txt_path.wstring(),false,L"",canceled); + Check(local_large.added==6000 && local_large.error.empty(),"local TXT above 1 MiB is imported in full"); std::filesystem::remove(txt_path); + canceled=true; Check(!ImportTrackerText(txt_base+L"/trackers.txt",true,L"",canceled).error.empty(),"canceled import does not make a request"); + std::vector trackers; std::wstring tracker_error; + Check(ParseTrackers(L"# comment\r\nudp://127.0.0.1:1234/announce\r\nhttp://127.0.0.1:5678/announce\r\nudp://127.0.0.1:1234/announce",trackers,tracker_error) && trackers.size()==2,"parse, deduplicate trackers"); + for(const auto& bad:{L"ftp://example.test/announce",L"file:///secret",L"udp://host:99999/announce",L"http://user:password@host/a",L"udp://host/announce",L"http://bad host/a"}) Check(!ParseTrackers(bad,trackers,tracker_error),"reject unsupported or invalid trackers"); + if(import_only) { std::cout<<"PASS: uncapped tracker parsing, local/online TXT above 1 MiB, normalization and validation\n"; return 0; } + auto transport=http::CreateDefaultTransport(); + const std::string data(256*1024,'X'); + for(const auto& route:{L"/file.bin",L"/no-rest.bin"}) for(int offset:{0,711,262144}) { + http::Request request; request.url=base+route; request.range_offset=offset; + auto opened=transport->Open(request); Check(!!opened.stream,"open FTP stream"); + auto expected=opened.stream->Headers().status==200?data:data.substr(offset); + Check(Drain(*opened.stream)==expected,"FTP payload, restart fallback and resumed payload"); + } + http::Request authenticated; authenticated.url=base+L"/file.bin"; authenticated.url.insert(6,L"user:pass@"); + auto login=transport->Open(authenticated); Check(login.stream && Drain(*login.stream)==data,"FTP URL authentication"); + http::Request missing; missing.url=base+L"/missing.bin"; Check(!transport->Open(missing).stream,"FTP missing file reports failure"); + ProxySettings proxy; proxy.type=1; proxy.host=L"127.0.0.1"; proxy.port=argv[3]; proxy.user=L"test"; proxy.password=L"pw"; + std::wstring proxy_error; Check(ValidateProxy(proxy,proxy_error),"validate HTTP proxy"); + auto broken=proxy; broken.type=-1; SetCurrentProxy(broken); + http::Request fail_closed; fail_closed.url=L"http://127.0.0.1:1/"; + Check(transport->Open(fail_closed).kind==http::OpenError::kInvalidRequest,"invalid saved proxy fails closed"); + SetCurrentProxy(proxy); + http::Request proxied; proxied.url=L"http://proxy-only.invalid/file"; + auto through=transport->Open(proxied); Check(through.stream && Drain(*through.stream)=="proxied-payload","HTTP authenticated proxy without local target DNS"); + http::Request ftp_proxy; ftp_proxy.url=base+L"/file.bin"; + auto ftp_through=transport->Open(ftp_proxy); Check(ftp_through.stream && Drain(*ftp_through.stream)==data,"FTP control and data through authenticated HTTP CONNECT proxy"); + auto wrong_password=proxy; wrong_password.password=L"wrong"; SetCurrentProxy(wrong_password); + auto refused=transport->Open(proxied); Check(refused.stream && refused.stream->Headers().status==407,"HTTP proxy authentication failure is not bypassed"); + SetCurrentProxy(proxy); + proxied.range_offset=4; through=transport->Open(proxied); Check(through.stream && through.stream->Headers().status==206 && Drain(*through.stream)=="ied-payload","proxy HTTP resume"); + proxied.range_offset=0; proxied.url=std::wstring(argv[5])+L"/trackers.txt"; Check(!transport->Open(proxied).stream,"HTTPS via CONNECT rejects untrusted certificate"); + proxy.type=2; proxy.port=argv[4]; SetCurrentProxy(proxy); + http::Request socks_request; socks_request.url=std::wstring(argv[2])+L"/trackers.txt"; socks_request.url.replace(7,9,L"proxy-only.invalid"); + wrong_password=proxy; wrong_password.password=L"wrong"; SetCurrentProxy(wrong_password); + Check(!transport->Open(socks_request).stream,"SOCKS5 authentication failure is not bypassed"); + SetCurrentProxy(proxy); + auto socks_response=transport->Open(socks_request); Check(socks_response.stream && !Drain(*socks_response.stream).empty(),"SOCKS5 authentication and remote DNS"); + ftp_through=transport->Open(ftp_proxy); Check(ftp_through.stream && Drain(*ftp_through.stream)==data,"FTP through authenticated SOCKS5 proxy"); + SetCurrentProxy({}); + std::wstring name,identity; + Check(!ParseMagnet(L"magnet:?xt=urn:btih:invalid",name,identity),"reject malformed info hash"); + Check(IsLocalDownloadLink(L"ftp://127.0.0.1/file") && IsLocalDownloadLink(L"magnet:?xt=urn:btih:0123456789012345678901234567890123456789"),"local startup accepts FTP and magnet schemes"); + auto root=std::filesystem::temp_directory_path()/(L"TTDownloader_protocol_test_"+std::to_wstring(GetCurrentProcessId())); + std::filesystem::create_directories(root/L"seed"); std::filesystem::create_directories(root/L"download"); + const std::string payload(2*1024*1024,'T'); + { std::ofstream out(root/L"seed"/L"payload.bin",std::ios::binary); out.write(payload.data(),payload.size()); } + lt::file_storage files; files.add_file("payload.bin",payload.size()); + lt::create_torrent creator(files,16*1024); lt::error_code ec; + lt::set_piece_hashes(creator,platform::ToUtf8((root/L"seed").wstring()),ec); Check(!ec,"hash local seed"); + auto metadata=std::make_shared(creator.generate()); + lt::settings_pack settings; + settings.set_bool(lt::settings_pack::enable_dht,false); settings.set_bool(lt::settings_pack::enable_lsd,false); + settings.set_bool(lt::settings_pack::enable_upnp,false); settings.set_bool(lt::settings_pack::enable_natpmp,false); + settings.set_str(lt::settings_pack::listen_interfaces,"127.0.0.1:0"); + settings.set_int(lt::settings_pack::upload_rate_limit,512*1024); + { + lt::session seeder(settings); lt::add_torrent_params params; params.ti=metadata; + params.save_path=platform::ToUtf8((root/L"seed").wstring()); params.flags|=lt::torrent_flags::seed_mode; + params.flags&=~lt::torrent_flags::auto_managed; params.flags&=~lt::torrent_flags::paused; + auto handle=seeder.add_torrent(params,ec); Check(!ec,"start local seed"); + auto deadline=GetTickCount64()+10000; + while(!seeder.listen_port() && GetTickCount64()Open(register_seed); Check(registered.stream && Drain(*registered.stream)=="OK","register local tracker peer"); + auto magnet=platform::FromUtf8(lt::make_magnet_uri(*metadata)); + Check(ParseMagnet(magnet,name,identity),"parse valid magnet"); + { + TorrentTransfer tls(magnet,(root/L"tls").wstring(),(root/L"tls.resume").wstring(),true,{std::wstring(argv[5])+L"/announce"}); + bool rejected=false; std::wstring tls_diagnostic; auto until=GetTickCount64()+20000; + while(GetTickCount64()0) { Check(transfer.Save(false),"checkpoint active torrent without pausing"); checkpoint=true; proxy.type=2; proxy.port=argv[4]; SetCurrentProxy(proxy); transfer.RefreshProxy(); } + if(state.complete) { finished=true; break; } Sleep(100); + } + if(!finished) throw std::runtime_error("metadata stalled: "+platform::ToUtf8(last_diagnostic)); + Check(checkpoint,"periodic metadata checkpoint was exercised"); + Check(finished,"magnet retrieves metadata and downloads from loopback peer"); + Check(transfer.Save(),"save torrent resume metadata"); + transfer.SetTrackers({}); Check(transfer.Poll().trackers==0,"remove global trackers from live transfer"); + } + TorrentTransfer resumed(magnet,(root/L"download").wstring(),(root/L"state.resume").wstring(),true); + Check(resumed.Poll().trackers==0,"old global trackers do not return from resume data"); + bool complete=false; deadline=GetTickCount64()+15000; + while(GetTickCount64()(input)),{}); + Check(received==payload,"torrent bytes match verified local seed"); input.close(); std::filesystem::remove_all(root); + std::cout<<"PASS: local FTP full/resume/restart and real magnet metadata, payload verification and recovery\n"; + return 0; + } catch(const std::exception& error) { std::cerr<<"FAIL: "< + + + Debugx64 + Releasex64 + + {A39CD514-FA46-40A5-84B3-DA232EB55FC2}false + + Applicationv143Unicode + + $(ProjectDir)..\bin\tests\$(Configuration)\$(ProjectDir)..\obj\protocol_tests\$(Configuration)\ + + + stdcpp20/utf-8 %(AdditionalOptions)Sync + NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions) + $(ProjectDir)..\src;%(AdditionalIncludeDirectories) + MultiThreadedDebug + MultiThreaded + + Console6.01 + + + + + + + + + + + diff --git a/client/tests/proxy_fixture.py b/client/tests/proxy_fixture.py new file mode 100644 index 0000000..5ba3d97 --- /dev/null +++ b/client/tests/proxy_fixture.py @@ -0,0 +1,69 @@ +import socket,socketserver,select,base64,urllib.parse,http.client +class HTTPProxy(socketserver.StreamRequestHandler): + connects=0 + gets=0 + def handle(self): + try: + line=self.rfile.readline().decode().strip(); method,target,_=line.split(' ',2); headers={} + while True: + line=self.rfile.readline() + if line in (b'\r\n',b'\n',b''): break + key,value=line.decode().split(':',1); headers[key.lower()]=value.strip() + expected='Basic '+base64.b64encode(b'test:pw').decode() + if headers.get('proxy-authorization')!=expected: + self.wfile.write(b'HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="local"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'); return + if method=='CONNECT': + host,port=target.rsplit(':',1); port=int(port) + if host not in ('127.0.0.1','localhost'): return + with socket.create_connection(('127.0.0.1',port),5) as peer: + HTTPProxy.connects+=1; self.wfile.write(b'HTTP/1.1 200 Connection established\r\n\r\n'); self.wfile.flush(); pump(self.connection,peer) + else: + HTTPProxy.gets+=1 + parsed=urllib.parse.urlsplit(target) + if parsed.hostname in ('127.0.0.1','localhost'): + connection=http.client.HTTPConnection('127.0.0.1',parsed.port,timeout=5) + connection.request('GET',parsed.path+('?' + parsed.query if parsed.query else '')) + response=connection.getresponse(); data=response.read(); connection.close() + self.wfile.write(b'HTTP/1.1 200 OK\r\nContent-Length: '+str(len(data)).encode()+b'\r\nConnection: close\r\n\r\n'+data); return + data=b'proxied-payload'; code=b'200 OK'; extra=b'' + if 'range' in headers: + start=int(headers['range'].split('=')[1].split('-')[0]); data=data[start:]; code=b'206 Partial Content'; extra=('Content-Range: bytes '+str(start)+'-14/15\r\n').encode() + self.wfile.write(b'HTTP/1.1 '+code+b'\r\n'+extra+b'Content-Length: '+str(len(data)).encode()+b'\r\nConnection: close\r\n\r\n'+data) + except (OSError,ValueError): pass +class SOCKSProxy(socketserver.StreamRequestHandler): + connections=0 + domains=0 + def handle(self): + def read(n): + data=self.rfile.read(n) + if len(data)!=n: raise OSError('short SOCKS frame') + return data + try: + version,n=read(2); methods=read(n) + if version!=5 or 2 not in methods: self.wfile.write(b'\x05\xff'); return + self.wfile.write(b'\x05\x02'); self.wfile.flush() + version,n=read(2); user=read(n); password=read(read(1)[0]) + if user!=b'test' or password!=b'pw': self.wfile.write(b'\x01\x01'); return + self.wfile.write(b'\x01\x00'); self.wfile.flush() + version,command,_,kind=read(4) + if kind==1: host=socket.inet_ntoa(read(4)) + elif kind==3: host=read(read(1)[0]).decode(); SOCKSProxy.domains+=1 + elif kind==4: host=socket.inet_ntop(socket.AF_INET6,read(16)) + else: return + port=int.from_bytes(read(2),'big') + if command!=1: self.wfile.write(b'\x05\x07\x00\x01'+b'\0'*6); return + if host not in ('127.0.0.1','localhost','proxy-only.invalid'): return + with socket.create_connection(('127.0.0.1',port),5) as peer: + SOCKSProxy.connections+=1; self.wfile.write(b'\x05\x00\x00\x01\x7f\x00\x00\x01'+port.to_bytes(2,'big')); self.wfile.flush(); pump(self.connection,peer) + except (OSError,ValueError): pass +def pump(a,b): + while True: + ready,_,_=select.select([a,b],[],[],10) + if not ready: return + for source in ready: + data=source.recv(65536) + if not data: return + (b if source is a else a).sendall(data) +class ProxyServer(socketserver.ThreadingTCPServer): + allow_reuse_address=True + daemon_threads=True diff --git a/client/tests/run_protocol_tests.py b/client/tests/run_protocol_tests.py new file mode 100644 index 0000000..2a2fa30 --- /dev/null +++ b/client/tests/run_protocol_tests.py @@ -0,0 +1,79 @@ +import socket,socketserver,threading,subprocess,sys,struct,urllib.parse,ssl,tempfile +from proxy_fixture import HTTPProxy,SOCKSProxy,ProxyServer +from http.server import ThreadingHTTPServer,BaseHTTPRequestHandler +DATA=b'X'*(256*1024) +class FTP(socketserver.StreamRequestHandler): + def handle(self): + listener=None; offset=0; no_rest=False + def reply(text): self.wfile.write((text+'\r\n').encode()); self.wfile.flush() + reply('220 local test FTP') + try: + for line in self.rfile: + command,_,arg=line.decode().strip().partition(' '); command=command.upper() + if command=='USER': reply('331 password') + elif command=='PASS': reply('230 logged in') + elif command=='SYST': reply('215 UNIX Type: L8') + elif command=='PWD': reply('257 "/"') + elif command=='FEAT': reply('211-Features\r\n SIZE\r\n REST STREAM\r\n211 End') + elif command in ('TYPE','CWD','OPTS','NOOP'): reply('200 OK') + elif command=='SIZE': + no_rest='no-rest' in arg; reply('550 missing' if 'missing' in arg else '213 '+str(len(DATA))) + elif command=='MDTM': reply('213 20261120000000') + elif command in ('EPSV','PASV'): + if listener: listener.close() + listener=socket.socket(); listener.bind(('127.0.0.1',0)); listener.listen(); listener.settimeout(10); port=listener.getsockname()[1] + reply('229 Entering Extended Passive Mode (|||'+str(port)+'|)' if command=='EPSV' else '227 Entering Passive Mode (127,0,0,1,'+str(port//256)+','+str(port%256)+')') + elif command=='REST': + if no_rest: reply('502 restart unavailable') + else: offset=int(arg); reply('350 restart accepted') + elif command=='RETR': + if 'no-rest' in arg and offset: + offset=0; reply('550 restart not supported'); continue + reply('150 data') + with listener.accept()[0] as peer: peer.sendall(DATA[offset:]) + listener.close(); listener=None; offset=0; reply('226 transfer complete') + elif command=='QUIT': reply('221 bye'); break + else: reply('502 unsupported') + except (ConnectionError,OSError): pass + finally: + if listener: listener.close() +class Server(socketserver.ThreadingTCPServer): + allow_reuse_address=True + daemon_threads=True +class Tracker(BaseHTTPRequestHandler): + peer_port=0 + announces=0 + def log_message(self,*args): pass + def do_GET(self): + parsed=urllib.parse.urlsplit(self.path) + if parsed.path=='/trackers.txt': body=b'\xef\xbb\xbfudp://127.0.0.1:1234/announce\nhttp://127.0.0.1:8080/announce\nudp://127.0.0.1:1234/announce\nhttps://unsupported.test/announce\n' + elif parsed.path=='/large.txt': body=b''.join(b'https://tracker.example/'+str(i).encode()+b'/'+b'a'*180+b'\n' for i in range(6000)) + elif parsed.path=='/missing.txt': + self.send_response(404); self.end_headers(); return + elif parsed.path=='/redirect.txt': + self.send_response(302); self.send_header('Location','/trackers.txt'); self.end_headers(); return + elif parsed.path=='/seed': + Tracker.peer_port=int(urllib.parse.parse_qs(parsed.query)['port'][0]); body=b'OK' + else: + Tracker.announces+=1 + peers=socket.inet_aton('127.0.0.1')+struct.pack('!H',Tracker.peer_port) + body=b'd8:intervali1e5:peers6:'+peers+b'e' + self.send_response(200); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body) +if '--tracker-import-only' in sys.argv[2:]: + with ThreadingHTTPServer(('127.0.0.1',0),Tracker) as tracker: + threading.Thread(target=tracker.serve_forever,daemon=True).start() + result=subprocess.run([sys.argv[1],'--tracker-import-tests','http://127.0.0.1:'+str(tracker.server_address[1])],timeout=60) + tracker.shutdown() + sys.exit(result.returncode) +with tempfile.TemporaryDirectory(prefix='TTDownloader_tls_test_') as certificate_dir: + subprocess.run([sys.argv[1],'--tls-fixture',certificate_dir],check=True,timeout=20) + context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); context.load_cert_chain(certificate_dir+'/cert.pem',certificate_dir+'/key.pem') + with Server(('127.0.0.1',0),FTP) as server, ThreadingHTTPServer(('127.0.0.1',0),Tracker) as tracker, ThreadingHTTPServer(('127.0.0.1',0),Tracker) as secure, ProxyServer(('127.0.0.1',0),HTTPProxy) as http_proxy, ProxyServer(('127.0.0.1',0),SOCKSProxy) as socks: + secure.socket=context.wrap_socket(secure.socket,server_side=True) + for service in (server,tracker,secure,http_proxy,socks): threading.Thread(target=service.serve_forever,daemon=True).start() + result=subprocess.run([sys.argv[1],'ftp://127.0.0.1:'+str(server.server_address[1]),'http://127.0.0.1:'+str(tracker.server_address[1]),str(http_proxy.server_address[1]),str(socks.server_address[1]),'https://127.0.0.1:'+str(secure.server_address[1])],timeout=160) + for service in (server,tracker,secure,http_proxy,socks): service.shutdown() + print("fixture paths:", Tracker.announces, HTTPProxy.gets, HTTPProxy.connects, SOCKSProxy.connections, SOCKSProxy.domains) + if result.returncode==0: + assert Tracker.announces>0 and HTTPProxy.gets>0 and HTTPProxy.connects>0 and SOCKSProxy.connections>0 and SOCKSProxy.domains>0,'proxy or tracker path was not exercised' + sys.exit(result.returncode) diff --git a/client/ttdownloader.vcxproj b/client/ttdownloader.vcxproj index 6c4b196..972cb6f 100644 --- a/client/ttdownloader.vcxproj +++ b/client/ttdownloader.vcxproj @@ -49,14 +49,14 @@ $(ProjectDir)bin\ $(ProjectDir)obj\$(PlatformName)\$(ProjectName)\$(Configuration)\ $(ProjectName)_d - $(ProjectDir)..\third_party\sqlite3;$(IncludePath) + $(ProjectDir)src;$(ProjectDir)..\third_party\sqlite3;$(IncludePath) false $(ProjectDir)bin\ $(ProjectDir)obj\$(PlatformName)\$(ProjectName)\$(Configuration)\ $(ProjectName) - $(ProjectDir)..\third_party\sqlite3;$(IncludePath) + $(ProjectDir)src;$(ProjectDir)..\third_party\sqlite3;$(IncludePath) @@ -99,34 +99,43 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - + - - + + NotUsing NotUsing - - - - - + + + + + + + - - + + + Create Create @@ -141,6 +150,7 @@ {19F8F655-C0F5-4AD9-B999-58D23F95AB43} + diff --git a/client/ttdownloader.vcxproj.filters b/client/ttdownloader.vcxproj.filters new file mode 100644 index 0000000..b6b135d --- /dev/null +++ b/client/ttdownloader.vcxproj.filters @@ -0,0 +1,160 @@ + + + + + {61AB5C52-DC99-5076-9ED2-8E4091F3F53E} + + + {28072FAA-C6AF-57EA-9FE4-9961F1A090A1} + + + {8DCDF7C6-007A-5D99-AED6-9F3A728AB6A3} + + + {3141C391-E045-5652-AE7E-3AAAC72DBCDC} + + + {7950FDE3-A3D0-5600-B5BF-C323B11A8E9A} + + + {FF24B64F-4481-5313-9B84-6B2F09ED9E30} + + + {60E2AA30-3F13-5718-8288-377F2BCE6521} + + + {E14F1BCF-FCA5-512E-BE8A-D1070E545975} + + + {6B0BE5C8-E22C-5E72-9297-7EECFB1B61AC} + + + {9CD58531-16F7-5BBA-8679-2CC7222B2887} + + + + + ui + + + app + + + engine + + + transport + + + engine + + + ui + + + ui + + + settings + + + settings + + + settings + + + integration + + + integration + + + engine + + + transport + + + transport + + + ui + + + integration + + + ui + + + settings + + + platform + + + 入口与预编译头 + + + storage + + + ui + + + integration + + + 外部源码 + + + 外部源码 + + + engine + + + transport + + + settings + + + engine + + + transport + + + transport + + + ui + + + integration + + + 入口与预编译头 + + + ui + + + ui + + + ui + + + storage + + + 入口与预编译头 + + + 外部源码 + + + \ No newline at end of file diff --git a/test.cmd b/test.cmd index b0b6644..f9f142e 100644 --- a/test.cmd +++ b/test.cmd @@ -7,6 +7,8 @@ if not defined TTUI_MSBUILD ( echo MSBuild not found. Install Visual Studio 2022 C++ workload. exit /b 1 ) +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0third_party\prepare.ps1" -Configuration %TTUI_TEST_CONFIG% +if errorlevel 1 exit /b 1 "%TTUI_MSBUILD%" "%~dp0ui\ttui\tests\smoke.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal if errorlevel 1 exit /b 1 "%TTUI_MSBUILD%" "%~dp0client\tests\http_transport_tests.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal @@ -15,6 +17,8 @@ if errorlevel 1 exit /b 1 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 +"%TTUI_MSBUILD%" "%~dp0client\tests\protocol_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" @@ -33,6 +37,11 @@ if errorlevel 1 ( popd exit /b 1 ) +python "%~dp0client\tests\run_protocol_tests.py" "%~dp0client\bin\tests\%TTUI_TEST_CONFIG%\protocol_tests.exe" +if errorlevel 1 ( + popd + exit /b 1 +) node --test "%~dp0browser\tests\extension.test.mjs" if errorlevel 1 ( popd diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt new file mode 100644 index 0000000..0254264 --- /dev/null +++ b/third_party/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.20) +project(TTDownloaderDependencies LANGUAGES C CXX) +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +add_compile_definitions(_WIN32_WINNT=0x0601 WINVER=0x0601 NOMINMAX) +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(static_runtime ON CACHE BOOL "" FORCE) +set(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/boost_1_86_0") +set(Boost_NO_BOOST_CMAKE ON) +set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL FALSE) +set(OPENSSL_USE_STATIC_LIBS TRUE) +set(OPENSSL_MSVC_STATIC_RT TRUE) +set(OPENSSL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/openssl/Release") +set(OPENSSL_INCLUDE_DIR "${OPENSSL_ROOT_DIR}/include") +set(OPENSSL_SSL_LIBRARY "${OPENSSL_ROOT_DIR}/lib/libssl.lib") +set(OPENSSL_CRYPTO_LIBRARY "${OPENSSL_ROOT_DIR}/lib/libcrypto.lib") +set(build_tests OFF CACHE BOOL "" FORCE) +set(build_examples OFF CACHE BOOL "" FORCE) +add_subdirectory(libtorrent-rasterbar-2.0.11) +target_compile_options(torrent-rasterbar PRIVATE /MP4) +get_directory_property(lt_definitions DIRECTORY libtorrent-rasterbar-2.0.11 COMPILE_DEFINITIONS) +list(REMOVE_ITEM lt_definitions "_WIN32_WINNT=0x0A00") +set_property(DIRECTORY libtorrent-rasterbar-2.0.11 PROPERTY COMPILE_DEFINITIONS "${lt_definitions}") + +set(BUILD_CURL_EXE OFF CACHE BOOL "" FORCE) +set(BUILD_TESTING OFF CACHE BOOL "" FORCE) +set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) +set(CURL_STATIC_CRT ON CACHE BOOL "" FORCE) +set(CURL_TARGET_WINDOWS_VERSION 0x0601 CACHE STRING "" FORCE) +set(CURL_USE_SCHANNEL ON CACHE BOOL "" FORCE) +set(CURL_USE_OPENSSL OFF CACHE BOOL "" FORCE) +set(CURL_USE_LIBPSL OFF CACHE BOOL "" FORCE) +set(CURL_ZLIB OFF CACHE BOOL "" FORCE) +set(CURL_BROTLI OFF CACHE BOOL "" FORCE) +set(CURL_ZSTD OFF CACHE BOOL "" FORCE) +set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) +set(CURL_DISABLE_LDAPS ON CACHE BOOL "" FORCE) +set(HTTP_ONLY OFF CACHE BOOL "" FORCE) +add_subdirectory(curl-8.23.0) +set_target_properties(torrent-rasterbar libcurl_static PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") diff --git a/third_party/NOTICES.txt b/third_party/NOTICES.txt new file mode 100644 index 0000000..79dd8ac --- /dev/null +++ b/third_party/NOTICES.txt @@ -0,0 +1,422 @@ +TTDownloader protocol dependencies + + +libcurl 8.23.0 +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2026, Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. + + +libtorrent-rasterbar 2.0.11 +Copyright (c) 2003-2020, Arvid Norberg +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------ + +puff.c +Copyright (C) 2002, 2003 Mark Adler +For conditions of distribution and use, see copyright notice in puff.h +version 1.7, 3 Mar 2003 + +puff.c is a simple inflate written to be an unambiguous way to specify the +deflate format. It is not written for speed but rather simplicity. As a +side benefit, this code might actually be useful when small code is more +important than speed, such as bootstrap applications. For typical deflate +data, zlib's inflate() is about four times as fast as puff(). zlib's +inflate compiles to around 20K on my machine, whereas puff.c compiles to +around 4K on my machine (a PowerPC using GNU cc). If the faster decode() +function here is used, then puff() is only twice as slow as zlib's +inflate(). + +All dynamically allocated memory comes from the stack. The stack required +is less than 2K bytes. This code is compatible with 16-bit int's and +assumes that long's are at least 32 bits. puff.c uses the short data type, +assumed to be 16 bits, for arrays in order to conserve memory. The code +works whether integers are stored big endian or little endian. + +In the comments below are "Format notes" that describe the inflate process +and document some of the less obvious aspects of the format. This source +code is meant to supplement RFC 1951, which formally describes the deflate +format: + + http://www.zlib.org/rfc-deflate.html + +------------------------------------------------------------------------------ + +bindings/python/src/ + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ + +ed25519 implementation based on: + +Copyright (c) 2015 Orson Peters + +This software is provided 'as-is', without any express or implied warranty. In no event will the +authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial +applications, and to alter it and redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not claim that you wrote the + original software. If you use this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be misrepresented as + being the original software. + +3. This notice may not be removed or altered from any source distribution. + +------------------------------------------------------------------------------ + +src/sha1.cpp include/libtorrent/sha1.hpp + +SHA-1 in C +By Steve Reid +100% Public Domain + +------------------------------------------------------------------------------ + +include/libtorrent/_aux/route.h + + * Copyright (c) 2000-2008 Apple Inc. All rights reserved. + * + * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. The rights granted to you under the License + * may not be used to create, or enable the creation or redistribution of, + * unlawful or unlicensed copies of an Apple operating system, or to + * circumvent, violate, or enable the circumvention or violation of, any + * terms of an Apple operating system software license agreement. + * + * Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * Copyright (c) 1980, 1986, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)route.h 8.3 (Berkeley) 4/19/94 + * $FreeBSD: src/sys/net/route.h,v 1.36.2.1 2000/08/16 06:14:23 jayanth Exp $ + +------------------------------------------------------------------------------ + +src/sha256.cpp + +SHA-256. Adapted from LibTomCrypt. This code is Public Domain + + + +Boost 1.86.0 +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + + +OpenSSL 3.5.9 +Copyright The OpenSSL Project Authors. All Rights Reserved. +https://openssl.org/ + + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/third_party/README.md b/third_party/README.md new file mode 100644 index 0000000..cf2cced --- /dev/null +++ b/third_party/README.md @@ -0,0 +1,25 @@ +# Protocol dependencies + +Run `prepare.ps1 -Configuration Release` (or Debug). Requires CMake, MSVC v143 and Strawberry Perl. `build.cmd` and `test.cmd` invoke this automatically. First build downloads pinned official source archives, verifies SHA-256, and builds static libraries. Sources and artifacts are ignored by Git; the bootstrap script, hashes, CMake configuration and license notices are versioned. + +- libcurl 8.23.0: FTP/FTPS and proxied HTTP/HTTPS in the application router, Schannel TLS, static CRT; curl license. +- libtorrent-rasterbar 2.0.11: BitTorrent v1/v2 magnet, metadata, DHT and resume; BSD license plus bundled notices. Boost 1.86.0 supplies headers (Boost Software License). +- All builds define Windows 7 (`_WIN32_WINNT=0x0601`). The wrapper removes libtorrent's upstream CMake Windows 10 target definition without editing upstream sources. Runtime Windows 7 SP1 testing is still required before a compatibility release. +- OpenSSL 3.5.9 LTS (Apache-2.0) is built statically without assembly or loadable modules. libtorrent HTTPS trackers validate certificates against Windows ROOT. FTPS and proxied HTTPS use Schannel. +- Ship NOTICES.txt with application binaries. + +FTP supports passive binary transfers and REST resume, with restart on rejected resume. Credentials in FTP URLs are stored with the task URL in tasks.db; use anonymous URLs for tasks that must not persist credentials. Direct HTTP/HTTPS use WinHTTP; configured proxies use libcurl. + +Magnet tasks use dedicated BT- directories to isolate multi-file storage. libtorrent manages files and verification, while the engine owns task scheduling, throttled UI/SQLite updates and pause commands. Metadata and periodic resume snapshots are kept under LocalAppData/TTDownloader/resume/.resume. Tasks retain the existing single-active-task scheduler. Finishing a torrent stops the session; background seeding is not enabled. Deleting a magnet task retains downloaded files and resume data, and the dialog states that behavior. + +Protocol regression tests bind only 127.0.0.1, disable DHT/LSD/UPnP/NAT-PMP in test sessions and create temporary storage. They test a local FTP server and real magnet metadata/payload exchange with a local seeder. Browser auto capture remains restricted to observed HTTP/HTTPS GET; FTP/magnet are added through the desktop client or command line. + +## Tracker configuration + +Settings -> Tracker opens a native multiline editor. User settings are stored under HKCU/Software/TTDownloader/Trackers. UDP, HTTP and HTTPS URLs are validated and deduplicated. Saving applies through an engine command to the active magnet transfer and to queued/restored tasks. The original magnet trackers remain; saved global trackers are discarded when loading resume data and replaced with current settings. + +Default tracker seed list: https://github.com/ngosang/trackerslist (three UDP entries selected from trackers_best.txt on 2026-11-21). These addresses do not guarantee availability or peers for a particular hash. DHT uses the bootstrap endpoints documented by libtorrent at https://www.libtorrent.org/reference-Settings.html. Metadata status reports connected peers, DHT routing nodes, tracker count and tracker errors. + +## Proxy configuration + +Settings -> Proxy supports direct, HTTP and SOCKS5 with optional credentials, encrypted with current-user DPAPI. HTTP proxies cannot carry UDP Tracker/DHT. SOCKS5 resolves hostnames remotely; UDP requires server support. Saving rebuilds active magnet sessions; existing HTTP/FTP streams require pause/resume. Failures do not fall back to direct. Tests use authenticated loopback proxies and reject self-signed HTTPS certificates without changing system trust. diff --git a/third_party/build-openssl.ps1 b/third_party/build-openssl.ps1 new file mode 100644 index 0000000..1d0405c --- /dev/null +++ b/third_party/build-openssl.ps1 @@ -0,0 +1,33 @@ +param([ValidateSet('Debug','Release')][string]$Configuration='Release') +$ErrorActionPreference='Stop' +$root=$PSScriptRoot +$source=Join-Path $root 'openssl-3.5.9' +$prefix=Join-Path $root ('openssl/'+$Configuration) +if((Test-Path (Join-Path $prefix 'lib/libssl.lib')) -and (Test-Path (Join-Path $prefix 'lib/libcrypto.lib')) -and (Test-Path (Join-Path $prefix 'include/openssl/configuration.h'))) { exit 0 } +$perl=(Get-Command perl -ErrorAction SilentlyContinue).Source +if(!$perl -and (Test-Path C:/Strawberry/perl/bin/perl.exe)) { $perl='C:/Strawberry/perl/bin/perl.exe' } +if(!$perl) { throw 'Strawberry Perl is required to build OpenSSL' } +$vs=& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$build=Join-Path $root ('build/openssl-'+$Configuration) +New-Item -ItemType Directory -Force $build | Out-Null +$make='nmake /nologo' +$mode=if($Configuration -eq 'Debug'){'--debug'}else{'--release'} +$batch=Join-Path $build 'build.cmd' +@" +@echo off +call "$vs\VC\Auxiliary\Build\vcvars64.bat" >nul +if errorlevel 1 exit /b 1 +set "PATH=$(Split-Path $perl);%PATH%" +set "CL=/FS" +set "LC_ALL=C" +set "LANG=C" +cd /d "$build" +"$perl" "$source\Configure" VC-WIN64A $mode no-shared no-module no-asm no-tests no-apps no-docs no-legacy no-ml-kem no-ml-dsa no-slh-dsa -D_WIN32_WINNT=0x0601 --prefix="$prefix" --openssldir="$prefix\ssl" --libdir=lib +if errorlevel 1 exit /b 1 +$make +if errorlevel 1 exit /b 1 +$make install_sw +exit /b %ERRORLEVEL% +"@ | Set-Content -LiteralPath $batch -Encoding ASCII +& cmd /c $batch +if($LASTEXITCODE) { throw 'OpenSSL build failed' } diff --git a/third_party/dependencies.props b/third_party/dependencies.props new file mode 100644 index 0000000..31d89f6 --- /dev/null +++ b/third_party/dependencies.props @@ -0,0 +1,12 @@ + + + $(MSBuildThisFileDirectory)openssl\Release\include;$(MSBuildThisFileDirectory)curl-8.23.0\include;$(MSBuildThisFileDirectory)libtorrent-rasterbar-2.0.11\include;$(MSBuildThisFileDirectory)boost_1_86_0;%(AdditionalIncludeDirectories) + TORRENT_USE_OPENSSL;TORRENT_USE_LIBCRYPTO;TORRENT_SSL_PEERS;WIN32_LEAN_AND_MEAN;CURL_STATICLIB;BOOST_ALL_NO_LIB;BOOST_ASIO_ENABLE_CANCELIO;BOOST_ASIO_NO_DEPRECATED;BOOST_EXCEPTION_DISABLE;BOOST_ASIO_HAS_STD_CHRONO;%(PreprocessorDefinitions) + TORRENT_USE_ASSERTS;TORRENT_USE_OPENSSL;TORRENT_USE_LIBCRYPTO;TORRENT_SSL_PEERS;WIN32_LEAN_AND_MEAN;CURL_STATICLIB;BOOST_ALL_NO_LIB;BOOST_ASIO_ENABLE_CANCELIO;BOOST_ASIO_NO_DEPRECATED;BOOST_EXCEPTION_DISABLE;BOOST_ASIO_HAS_STD_CHRONO;%(PreprocessorDefinitions) + + $(MSBuildThisFileDirectory)openssl\$(Configuration)\lib;$(MSBuildThisFileDirectory)build\lib\$(Configuration);%(AdditionalLibraryDirectories) + libssl.lib;libcrypto.lib;user32.lib;gdi32.lib;torrent-rasterbar.lib;dbghelp.lib;ws2_32.lib;iphlpapi.lib;bcrypt.lib;crypt32.lib;secur32.lib;normaliz.lib;wldap32.lib;%(AdditionalDependencies) + libcurl-d.lib;%(AdditionalDependencies) + libcurl.lib;%(AdditionalDependencies) + + \ No newline at end of file diff --git a/third_party/prepare.ps1 b/third_party/prepare.ps1 new file mode 100644 index 0000000..a5983ba --- /dev/null +++ b/third_party/prepare.ps1 @@ -0,0 +1,37 @@ +param([ValidateSet('Debug','Release')][string]$Configuration='Debug') +$ErrorActionPreference='Stop' +$root=$PSScriptRoot +$packages=@( + @('openssl','openssl-3.5.9','https://github.com/openssl/openssl/releases/download/openssl-3.5.9/openssl-3.5.9.tar.gz','603F5602E2EEF00D77FBD429D34DCD5822BB301757A1BC9CDB24C670F1EB859A'), + @('curl','curl-8.23.0','https://curl.se/download/curl-8.23.0.tar.gz','E3DE77CFA6367083C776A26647FC9F633B538C06C3BAA73D931A252AC8F72B49'), + @('libtorrent','libtorrent-rasterbar-2.0.11','https://github.com/arvidn/libtorrent/releases/download/v2.0.11/libtorrent-rasterbar-2.0.11.tar.gz','F0DB58580F4F29ADE6CC40FA4BA80E2C9A70C90265CD77332D3CDEC37ECF1E6D'), + @('boost','boost_1_86_0','https://archives.boost.io/release/1.86.0/source/boost_1_86_0.tar.gz','2575E74FFC3EF1CD0BABAC2C1EE8BDB5782A0EE672B1912DA40E5B4B591CA01F') +) +$curlName=if($Configuration -eq 'Debug'){'libcurl-d.lib'}else{'libcurl.lib'} +$library=Join-Path $root ('build/lib/'+$Configuration+'/torrent-rasterbar.lib') +$curlLibrary=Join-Path $root ('build/lib/'+$Configuration+'/'+$curlName) +if((Test-Path -LiteralPath $library) -and (Test-Path -LiteralPath $curlLibrary) -and (Test-Path (Join-Path $root ('openssl/'+$Configuration+'/lib/libssl.lib'))) -and (Test-Path (Join-Path $root ('openssl/'+$Configuration+'/lib/libcrypto.lib'))) -and (Test-Path (Join-Path $root ('openssl/'+$Configuration+'/include/openssl/configuration.h')))) { + if((Get-Item -LiteralPath $library).LastWriteTime -gt (Get-Item (Join-Path $root 'CMakeLists.txt')).LastWriteTime -and + (Get-Item -LiteralPath $curlLibrary).LastWriteTime -gt (Get-Item (Join-Path $root 'CMakeLists.txt')).LastWriteTime) { exit 0 } +} +New-Item -ItemType Directory -Force (Join-Path $root 'sources') | Out-Null +foreach($package in $packages) { + $archive=Join-Path $root ('sources/'+$package[0]+'.tar.gz') + if(!(Test-Path -LiteralPath $archive)) { Invoke-WebRequest -Uri $package[2] -OutFile $archive -UseBasicParsing } + $hashAlgorithm=[System.Security.Cryptography.SHA256]::Create() + $archiveStream=[System.IO.File]::OpenRead($archive) + try { $sourceHash=[BitConverter]::ToString($hashAlgorithm.ComputeHash($archiveStream)).Replace('-','') } + finally { $archiveStream.Dispose(); $hashAlgorithm.Dispose() } + if($sourceHash -ne $package[3]) { throw "Source checksum mismatch: $archive" } + if(!(Test-Path -LiteralPath (Join-Path $root $package[1]))) { + if($package[0] -eq 'boost') { & tar -xzf $archive -C $root boost_1_86_0/boost boost_1_86_0/LICENSE_1_0.txt } + else { & tar -xzf $archive -C $root } + if($LASTEXITCODE) { throw 'Source extraction failed' } + } +} +& (Join-Path $root 'build-openssl.ps1') -Configuration Release +if($Configuration -eq 'Debug') { & (Join-Path $root 'build-openssl.ps1') -Configuration Debug } +& cmake -S $root -B (Join-Path $root 'build') -A x64 +if($LASTEXITCODE) { throw 'Dependency configure failed' } +& cmake --build (Join-Path $root 'build') --config $Configuration --target torrent-rasterbar libcurl_static --parallel 4 +if($LASTEXITCODE) { throw 'Dependency build failed' } diff --git a/ui/ttui/include/ttui/window.h b/ui/ttui/include/ttui/window.h index b42892d..3043f44 100644 --- a/ui/ttui/include/ttui/window.h +++ b/ui/ttui/include/ttui/window.h @@ -52,7 +52,7 @@ public: float Width() const; float Height() const; void Place(HWND child, Rect rect); - HWND CreateEdit(int id, const wchar_t* cue); + HWND CreateEdit(int id, const wchar_t* cue,bool multiline=false); static std::wstring EditText(HWND edit); void FocusContent(); void ClearButtons(); diff --git a/ui/ttui/src/window.cpp b/ui/ttui/src/window.cpp index 72bf21c..3d01a62 100644 --- a/ui/ttui/src/window.cpp +++ b/ui/ttui/src/window.cpp @@ -150,8 +150,8 @@ void Window::Place(HWND child,Rect r) { MoveWindow(child,static_cast(r.left*Scale()),static_cast(r.top*Scale()), std::max(1,static_cast((r.right-r.left)*Scale())),std::max(1,static_cast((r.bottom-r.top)*Scale())),TRUE); } -HWND Window::CreateEdit(int id,const wchar_t* cue) { - HWND edit=CreateWindowExW(WS_EX_CLIENTEDGE,L"EDIT",L"",WS_CHILD|WS_VISIBLE|WS_TABSTOP|ES_AUTOHSCROLL, +HWND Window::CreateEdit(int id,const wchar_t* cue,bool multiline) { + HWND edit=CreateWindowExW(WS_EX_CLIENTEDGE,L"EDIT",L"",WS_CHILD|WS_VISIBLE|WS_TABSTOP|(multiline?(ES_MULTILINE|ES_AUTOVSCROLL|ES_WANTRETURN|WS_VSCROLL):ES_AUTOHSCROLL), 0,0,1,1,hwnd_,reinterpret_cast(static_cast(id)),GetModuleHandleW(nullptr),nullptr); SendMessageW(edit,WM_SETFONT,reinterpret_cast(impl_->font),TRUE); SendMessageW(edit,EM_SETCUEBANNER,FALSE,reinterpret_cast(cue)); @@ -276,7 +276,7 @@ void Window::Paint() { } LRESULT CALLBACK Window::EditProc(HWND edit,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data) { auto* self=reinterpret_cast(data); - if (msg==WM_KEYDOWN && wp==VK_RETURN) { self->OnCommand(GetDlgCtrlID(edit)); return 0; } + if (msg==WM_KEYDOWN && wp==VK_RETURN && !(GetWindowLongPtrW(edit,GWL_STYLE)&ES_MULTILINE)) { self->OnCommand(GetDlgCtrlID(edit)); return 0; } if (msg==WM_KEYDOWN && wp==VK_TAB) { HWND next=GetNextDlgTabItem(self->hwnd_,edit,GetKeyState(VK_SHIFT)<0); if (next && next!=edit && (GetKeyState(VK_SHIFT)<0 || GetDlgCtrlID(next)>GetDlgCtrlID(edit))) SetFocus(next); diff --git a/ui/ttui/tests/smoke.cpp b/ui/ttui/tests/smoke.cpp index 8dc77ef..48e1837 100644 --- a/ui/ttui/tests/smoke.cpp +++ b/ui/ttui/tests/smoke.cpp @@ -1,10 +1,13 @@ +#include "settings/proxy_settings.h" +#include "ui/proxy_form.h" #include "ttui/application.h" #include "ttui/window.h" #include "ttui/virtual_list.h" -#include "platform.h" -#include "task_store.h" -#include "settings_form.h" -#include "add_task_form.h" +#include "platform/platform.h" +#include "storage/task_store.h" +#include "ui/settings_form.h" +#include "ui/add_task_form.h" +#include "ui/tracker_form.h" #include #include #include @@ -44,6 +47,7 @@ private: }; int main() { try { + SetCurrentProxy({}); ttui::VirtualList list; list.Configure(100000,10); list.ScrollTo(999999); auto [first,last]=list.Visible(); Check(first==99990 && last==100000,"viewport end clamp"); @@ -143,6 +147,41 @@ int main() { settings.Close(); Check(closed==1,"appearance close callback once"); + int proxy_applies=0; + ProxyForm proxy(&appearance,[&] { ++proxy_applies; }); + Check(proxy.Create(window.GetHWND(),ProxyForm::kClassName.c_str(),L"Proxy test",620,380),"create proxy settings page"); + SendMessageW(proxy.GetHWND(),WM_COMMAND,12,0); + Check(IsWindowEnabled(GetDlgItem(proxy.GetHWND(),100)),"SOCKS5 enables proxy fields"); + Check(SendMessageW(GetDlgItem(proxy.GetHWND(),103),EM_GETPASSWORDCHAR,0,0)!=0,"proxy password is masked"); + SetWindowTextW(GetDlgItem(proxy.GetHWND(),100),L"bad/host"); + SendMessageW(proxy.GetHWND(),WM_COMMAND,1,0); + Check(proxy_applies==0,"invalid proxy cannot be saved or applied"); + proxy.Close(); + Check(proxy.Create(window.GetHWND(),ProxyForm::kClassName.c_str(),L"Proxy reopen",620,380) && GetDlgItem(proxy.GetHWND(),103),"proxy fields survive recreation"); + proxy.Close(); + int tracker_applies=0; + TrackerForm trackers(&appearance,[&](const auto&) { ++tracker_applies; }); + Check(trackers.Create(window.GetHWND(),TrackerForm::kClassName.c_str(),L"Tracker settings test",680,480),"create tracker settings page"); + auto tracker_edit=GetDlgItem(trackers.GetHWND(),100); + Check((GetWindowLongPtrW(tracker_edit,GWL_STYLE)&ES_MULTILINE)!=0,"tracker editor is native multiline edit"); + std::wstring long_edit(40000,L'x'); + SetWindowTextW(tracker_edit,L""); + SendMessageW(tracker_edit,EM_REPLACESEL,FALSE,reinterpret_cast(long_edit.c_str())); + Check(ttui::Window::EditText(tracker_edit)==long_edit,"tracker editor accepts typing and paste beyond 32767 characters"); + SetWindowTextW(tracker_edit,L"http://127.0.0.1:8080/announce"); + SendMessageW(tracker_edit,EM_SETSEL,-1,-1); SendMessageW(tracker_edit,WM_KEYDOWN,VK_RETURN,0); SendMessageW(tracker_edit,WM_CHAR,VK_RETURN,0); + Check(ttui::Window::EditText(tracker_edit).find(L'\n')!=std::wstring::npos && tracker_applies==0,"Return inserts newline instead of saving tracker page"); + SetWindowTextW(tracker_edit,L"file:///example.test/announce"); SendMessageW(trackers.GetHWND(),WM_COMMAND,1,0); + Check(tracker_applies==0 && trackers.IsOpen(),"invalid trackers cannot be silently saved"); + auto import_source=GetDlgItem(trackers.GetHWND(),101); Check(import_source!=nullptr,"online TXT source input exists"); + SetWindowTextW(import_source,L"http://127.0.0.1:1/trackers.txt"); + SendMessageW(trackers.GetHWND(),WM_COMMAND,4,0); + Check(!IsWindowEnabled(tracker_edit),"import runs in background and protects the editor from conflicting changes"); + trackers.Close(); + Check(trackers.Create(window.GetHWND(),TrackerForm::kClassName.c_str(),L"Tracker settings reopen",680,480) && GetDlgItem(trackers.GetHWND(),100),"tracker controls survive window recreation"); + Check(IsWindowEnabled(GetDlgItem(trackers.GetHWND(),100)) && GetDlgItem(trackers.GetHWND(),101),"closing an import cannot disable the next window instance"); + trackers.Close(); + int submissions=0; std::wstring submitted_url,submitted_directory; AddTaskForm add(&appearance,[&](const std::wstring& url,const std::wstring& directory) { diff --git a/ui/ttui/tests/smoke.vcxproj b/ui/ttui/tests/smoke.vcxproj index 2e96180..141a5db 100644 --- a/ui/ttui/tests/smoke.vcxproj +++ b/ui/ttui/tests/smoke.vcxproj @@ -23,7 +23,8 @@ Consoleuuid.lib;%(AdditionalDependencies) - TurnOffAllWarnings + TurnOffAllWarnings {19F8F655-C0F5-4AD9-B999-58D23F95AB43} - + +