分离 HTTP 传输接口与下载任务调度
封装 WinHTTP 请求和响应流,保留任务引擎中的续传、文件写入、重试与持久化策略。增加本地 HTTP 契约测试和后端替换说明。
This commit is contained in:
1 parent
db38ec5c03
commit
6c810c3b4f
13 files changed
+551
-208
No files matched your search
@@ -34,6 +34,15 @@
|
|||||||
- 桌面端未运行、通信失败或任务重复时,应向用户提供明确状态,不得静默丢任务。
|
- 桌面端未运行、通信失败或任务重复时,应向用户提供明确状态,不得静默丢任务。
|
||||||
- 不默认拦截浏览器全部下载;自动接管、站点规则和过滤策略应可配置。
|
- 不默认拦截浏览器全部下载;自动接管、站点规则和过滤策略应可配置。
|
||||||
|
|
||||||
|
## HTTP 传输层边界
|
||||||
|
|
||||||
|
- `client/src/http_transport.h` 定义不含 Windows/WinHTTP 原生句柄的请求、响应和同步流接口;传输层不依赖 TaskInfo、TaskStore、窗口或下载任务命令。
|
||||||
|
- `client/src/winhttp_transport.cpp` 封装当前 WinHTTP 实现,负责 URL 解析、请求、响应头、网络数据读取及网络错误。HTTP 404/416 等状态原样交给调用方处理。
|
||||||
|
- `DownloadEngine` 只依赖传输接口,负责排队、文件写入、200/206/416 续传策略、重试、取消、进度和数据库节流;禁止在引擎中直接调用 WinHTTP API。
|
||||||
|
- 默认后端在 `client/src/http_transport.cpp` 组装;以后迁移 libcurl 时实现同一接口并修改此入口。引擎支持注入 Transport,便于测试和后端替换。
|
||||||
|
- Open/Read 是工作线程上的同步操作,暂停和退出在操作边界检查;每次操作有超时,不允许传输层自行重试、回调 UI 或访问数据库。响应流应在同一工作线程中销毁,确保网络句柄及时释放。
|
||||||
|
- `test.cmd Debug/Release` 包含仅绑定 127.0.0.1 的 HTTP 集成测试,不连接外部网站,不访问用户任务库。
|
||||||
|
|
||||||
## 第三方依赖
|
## 第三方依赖
|
||||||
|
|
||||||
- UI 引擎仅使用 Windows SDK,不再引入 NIM/Duilib;新增依赖仍须确认维护状态、MSVC 兼容性和许可证。
|
- UI 引擎仅使用 Windows SDK,不再引入 NIM/Duilib;新增依赖仍须确认维护状态、MSVC 兼容性和许可证。
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# HTTP 传输边界
|
||||||
|
|
||||||
|
`DownloadEngine → http::Transport → http::ResponseStream`。默认实现仍为 WinHTTP,本次没有引入 libcurl 或改变任务数据库结构。
|
||||||
|
|
||||||
|
## 文件职责
|
||||||
|
|
||||||
|
- `src/http_transport.h`:纯 C++20 请求/响应类型与传输接口,不暴露 HINTERNET、DWORD 或 WinHTTP 常量。
|
||||||
|
- `src/http_transport.cpp`:选择默认后端的组装入口。
|
||||||
|
- `src/winhttp_transport.cpp/.h`:WinHTTP 后端;构造工厂不联网,Open/Read 和响应流销毁都在下载工作线程发生。
|
||||||
|
- `src/download_engine.cpp`:任务队列与状态、文件写入、重试和暂停/删除处理、EngineEvent 以及 TaskStore。需要测试后端时可通过第二个构造函数注入 Transport。
|
||||||
|
|
||||||
|
传输层返回 200/206/416/404 等原始状态、Content-Length 和 Content-Range。引擎继续决定:200 从零截断写入;206 按偏移写入;416 清理分片再进入重试;其他非成功 HTTP 状态失败。服务器提前关闭或数据不足时,由引擎检查已写入长度并重试。新增后端仍须履行 Read 的有界读取和 EOF 契约。
|
||||||
|
|
||||||
|
## 超时和资源
|
||||||
|
|
||||||
|
Open/Read 是同步操作。Request 提供解析、连接、发送与接收超时;重试次数、重试间隔和暂停检查不属于传输层。引擎在读取前后处理命令,避免网络读取期间收到暂停/删除后继续写入新数据。当前仍在同一个下载线程顺序执行任务,并未新增多连接调度或异步网络取消。
|
||||||
|
|
||||||
|
WinHTTP session、connection、request 由响应流 RAII 持有,按 request → connection → session 顺序释放。直接使用固定缓冲区 WinHttpReadData,并以成功读取零字节判断 EOF;参考 [Microsoft WinHttpReadData](https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpreaddata)。超时可受系统轮询粒度影响,不承诺毫秒级取消。
|
||||||
|
|
||||||
|
保留 Windows 7 自动代理回退及 TLS 配置;64 位 Content-Length 通过文本查询和溢出检查获取。TLS 证书校验保持系统默认,不跳过证书错误。
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
运行根目录 `test.cmd Debug` 或 `test.cmd Release`。测试需要开发机安装 Python;Python 不属于客户端下载依赖。
|
||||||
|
|
||||||
|
`tests/http_transport_tests.vcxproj` 独立编译传输层,不链接下载调度器、TTUI 或 SQLite。Python runner 启动随机端口的 127.0.0.1 HTTP 服务,再在 C++ 工作线程执行测试,覆盖完整二进制读取、Range 请求、206、忽略 Range 的 200、416、404、重定向、chunked、超过 4GB 的长度元数据、长度溢出、超时、非法参数和提前关闭响应流。
|
||||||
|
|
||||||
|
这组测试验证传输契约,不等于完整下载器或 Windows 7 实机验收。未来添加 libcurl 后端后,应复用同一组契约测试,并补充不同 TLS 后端及系统代理测试。
|
||||||
+40
-208
@@ -2,27 +2,14 @@
|
|||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
#include "download_engine.h"
|
#include "download_engine.h"
|
||||||
|
|
||||||
#include <winhttp.h>
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <cwctype>
|
#include <cwctype>
|
||||||
|
|
||||||
#pragma comment(lib, "winhttp.lib")
|
|
||||||
|
|
||||||
namespace
|
namespace
|
||||||
{
|
{
|
||||||
namespace
|
|
||||||
{
|
|
||||||
struct UrlParts
|
|
||||||
{
|
|
||||||
std::wstring host;
|
|
||||||
std::wstring path;
|
|
||||||
INTERNET_PORT port = 0;
|
|
||||||
bool https = false;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
std::wstring Trim(const std::wstring& text)
|
std::wstring Trim(const std::wstring& text)
|
||||||
{
|
{
|
||||||
size_t begin = 0;
|
size_t begin = 0;
|
||||||
@@ -68,31 +55,6 @@ namespace
|
|||||||
return ::CreateDirectoryW(dir.c_str(), nullptr) == TRUE;
|
return ::CreateDirectoryW(dir.c_str(), nullptr) == TRUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CrackUrl(const std::wstring& url, UrlParts& parts)
|
|
||||||
{
|
|
||||||
URL_COMPONENTS components = {};
|
|
||||||
components.dwStructSize = sizeof(components);
|
|
||||||
components.dwSchemeLength = static_cast<DWORD>(-1);
|
|
||||||
components.dwHostNameLength = static_cast<DWORD>(-1);
|
|
||||||
components.dwUrlPathLength = static_cast<DWORD>(-1);
|
|
||||||
components.dwExtraInfoLength = static_cast<DWORD>(-1);
|
|
||||||
|
|
||||||
if (!::WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &components))
|
|
||||||
return false;
|
|
||||||
if (components.nScheme != INTERNET_SCHEME_HTTP && components.nScheme != INTERNET_SCHEME_HTTPS)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
parts.host.assign(components.lpszHostName, components.dwHostNameLength);
|
|
||||||
parts.path.assign(components.lpszUrlPath, components.dwUrlPathLength);
|
|
||||||
if (components.lpszExtraInfo != nullptr && components.dwExtraInfoLength > 0)
|
|
||||||
parts.path.append(components.lpszExtraInfo, components.dwExtraInfoLength);
|
|
||||||
if (parts.path.empty())
|
|
||||||
parts.path = L"/";
|
|
||||||
parts.port = components.nPort;
|
|
||||||
parts.https = components.nScheme == INTERNET_SCHEME_HTTPS;
|
|
||||||
return !parts.host.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
int HexDigit(wchar_t c)
|
int HexDigit(wchar_t c)
|
||||||
{
|
{
|
||||||
if (c >= L'0' && c <= L'9')
|
if (c >= L'0' && c <= L'9')
|
||||||
@@ -167,11 +129,11 @@ namespace
|
|||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::wstring FileNameFromUrl(const std::wstring& url)
|
std::wstring FileNameFromUrl(const std::wstring& url,const http::Transport& transport)
|
||||||
{
|
{
|
||||||
UrlParts parts;
|
http::UrlParts parts;
|
||||||
std::wstring path = url;
|
std::wstring path = url;
|
||||||
if (CrackUrl(url, parts))
|
if (transport.ParseUrl(url, parts))
|
||||||
path = parts.path;
|
path = parts.path;
|
||||||
|
|
||||||
size_t query = path.find_first_of(L"?#");
|
size_t query = path.find_first_of(L"?#");
|
||||||
@@ -240,68 +202,6 @@ namespace
|
|||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::wstring NetworkErrorText(DWORD code)
|
|
||||||
{
|
|
||||||
wchar_t* buffer = nullptr;
|
|
||||||
DWORD length = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
|
|
||||||
| FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, code, 0,
|
|
||||||
reinterpret_cast<wchar_t*>(&buffer), 0, nullptr);
|
|
||||||
if (length == 0 || buffer == nullptr)
|
|
||||||
{
|
|
||||||
HMODULE winhttp = ::GetModuleHandleW(L"winhttp.dll");
|
|
||||||
if (winhttp != nullptr)
|
|
||||||
{
|
|
||||||
length = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE
|
|
||||||
| FORMAT_MESSAGE_IGNORE_INSERTS, winhttp, code, 0,
|
|
||||||
reinterpret_cast<wchar_t*>(&buffer), 0, nullptr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (length == 0 || buffer == nullptr)
|
|
||||||
{
|
|
||||||
wchar_t fallback[32] = { 0 };
|
|
||||||
swprintf_s(fallback, L"错误码 %u", code);
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::wstring text(buffer, length);
|
|
||||||
::LocalFree(buffer);
|
|
||||||
while (!text.empty() && (text.back() == L'\r' || text.back() == L'\n' || text.back() == L' '))
|
|
||||||
text.pop_back();
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::wstring QueryHeaderText(HINTERNET request, DWORD query);
|
|
||||||
int64_t QueryContentLength(HINTERNET request) {
|
|
||||||
const std::wstring text=QueryHeaderText(request,WINHTTP_QUERY_CONTENT_LENGTH);
|
|
||||||
if (text.empty()) return 0;
|
|
||||||
int64_t value=0;
|
|
||||||
for (wchar_t ch:text) {
|
|
||||||
if (ch<L'0' || ch>L'9' || value>(INT64_MAX-(ch-L'0'))/10) return 0;
|
|
||||||
value=value*10+(ch-L'0');
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::wstring QueryHeaderText(HINTERNET request, DWORD query)
|
|
||||||
{
|
|
||||||
DWORD size = 0;
|
|
||||||
::WinHttpQueryHeaders(request, query, WINHTTP_HEADER_NAME_BY_INDEX,
|
|
||||||
WINHTTP_NO_OUTPUT_BUFFER, &size, WINHTTP_NO_HEADER_INDEX);
|
|
||||||
if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER || size == 0)
|
|
||||||
return std::wstring();
|
|
||||||
|
|
||||||
std::wstring text(size / sizeof(wchar_t), L'\0');
|
|
||||||
if (!::WinHttpQueryHeaders(request, query, WINHTTP_HEADER_NAME_BY_INDEX,
|
|
||||||
text.data(), &size, WINHTTP_NO_HEADER_INDEX))
|
|
||||||
return std::wstring();
|
|
||||||
|
|
||||||
text.resize(size / sizeof(wchar_t));
|
|
||||||
while (!text.empty() && text.back() == L'\0')
|
|
||||||
text.pop_back();
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
int64_t ParseContentRangeTotal(const std::wstring& value)
|
int64_t ParseContentRangeTotal(const std::wstring& value)
|
||||||
{
|
{
|
||||||
size_t slash = value.find_last_of(L'/');
|
size_t slash = value.find_last_of(L'/');
|
||||||
@@ -315,8 +215,11 @@ namespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
DownloadEngine::DownloadEngine(HWND notify_wnd)
|
DownloadEngine::DownloadEngine(HWND notify_wnd)
|
||||||
: notify_wnd_(notify_wnd)
|
:DownloadEngine(notify_wnd,http::CreateDefaultTransport()) {}
|
||||||
{
|
|
||||||
|
DownloadEngine::DownloadEngine(HWND notify_wnd,std::unique_ptr<http::Transport> transport)
|
||||||
|
:notify_wnd_(notify_wnd),transport_(std::move(transport)) {
|
||||||
|
if (!transport_) transport_=http::CreateDefaultTransport();
|
||||||
}
|
}
|
||||||
|
|
||||||
DownloadEngine::~DownloadEngine()
|
DownloadEngine::~DownloadEngine()
|
||||||
@@ -420,7 +323,7 @@ void DownloadEngine::ThreadMain()
|
|||||||
if (task.file_name.empty())
|
if (task.file_name.empty())
|
||||||
{
|
{
|
||||||
std::wstring dir = task.save_path;
|
std::wstring dir = task.save_path;
|
||||||
task.file_name = FileNameFromUrl(task.url);
|
task.file_name = FileNameFromUrl(task.url,*transport_);
|
||||||
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
||||||
store_.UpdateTarget(task.id, task.save_path, task.file_name);
|
store_.UpdateTarget(task.id, task.save_path, task.file_name);
|
||||||
}
|
}
|
||||||
@@ -527,8 +430,8 @@ void DownloadEngine::HandleAdd(const Command& cmd)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
UrlParts parts;
|
http::UrlParts parts;
|
||||||
if (!CrackUrl(url, parts))
|
if (!transport_->ParseUrl(url, parts))
|
||||||
{
|
{
|
||||||
PostRejected(L"仅支持有效的 HTTP/HTTPS 链接");
|
PostRejected(L"仅支持有效的 HTTP/HTTPS 链接");
|
||||||
return;
|
return;
|
||||||
@@ -556,7 +459,7 @@ void DownloadEngine::HandleAdd(const Command& cmd)
|
|||||||
|
|
||||||
TaskInfo task;
|
TaskInfo task;
|
||||||
task.url = url;
|
task.url = url;
|
||||||
task.file_name = FileNameFromUrl(url);
|
task.file_name = FileNameFromUrl(url,*transport_);
|
||||||
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
||||||
task.state = TaskState::kQueued;
|
task.state = TaskState::kQueued;
|
||||||
|
|
||||||
@@ -737,78 +640,18 @@ void DownloadEngine::Download(TaskInfo& task)
|
|||||||
DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
||||||
const std::wstring& part_path, std::wstring& error)
|
const std::wstring& part_path, std::wstring& error)
|
||||||
{
|
{
|
||||||
UrlParts parts;
|
const int64_t offset=GetFileSize(part_path);
|
||||||
if (!CrackUrl(task.url, parts))
|
http::Request request;
|
||||||
{
|
request.url=task.url;
|
||||||
error = L"无效的下载链接";
|
request.range_offset=offset;
|
||||||
return AttemptResult::kFatal;
|
auto opened=transport_->Open(request);
|
||||||
}
|
if (!opened.stream) {
|
||||||
|
error=opened.error;
|
||||||
using WinHttpHandle = std::unique_ptr<void, decltype(&::WinHttpCloseHandle)>;
|
return opened.kind==http::OpenError::kInvalidRequest?AttemptResult::kFatal:AttemptResult::kRetry;
|
||||||
WinHttpHandle session(::WinHttpOpen(L"TTDownloader/0.1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
|
||||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0), &::WinHttpCloseHandle);
|
|
||||||
const bool legacy_proxy=!session && ::GetLastError()==ERROR_INVALID_PARAMETER;
|
|
||||||
if (legacy_proxy)
|
|
||||||
session.reset(::WinHttpOpen(L"TTDownloader/0.1",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
|
|
||||||
WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0));
|
|
||||||
if (!session)
|
|
||||||
{
|
|
||||||
error = L"无法初始化网络连接";
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
if (legacy_proxy) {
|
|
||||||
DWORD protocols=WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
|
|
||||||
::WinHttpSetOption(session.get(),WINHTTP_OPTION_SECURE_PROTOCOLS,&protocols,sizeof(protocols));
|
|
||||||
}
|
}
|
||||||
::WinHttpSetTimeouts(session.get(), 15000, 15000, 15000, 4000);
|
auto stream=std::move(opened.stream);
|
||||||
|
const auto& response=stream->Headers();
|
||||||
WinHttpHandle connect(::WinHttpConnect(session.get(), parts.host.c_str(), parts.port, 0),
|
const unsigned status=response.status;
|
||||||
&::WinHttpCloseHandle);
|
|
||||||
if (!connect)
|
|
||||||
{
|
|
||||||
error = L"无法连接服务器";
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
|
|
||||||
WinHttpHandle request(::WinHttpOpenRequest(connect.get(), L"GET", parts.path.c_str(), nullptr,
|
|
||||||
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
|
|
||||||
parts.https ? WINHTTP_FLAG_SECURE : 0), &::WinHttpCloseHandle);
|
|
||||||
if (!request)
|
|
||||||
{
|
|
||||||
error = L"无法创建下载请求";
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
|
|
||||||
int64_t offset = GetFileSize(part_path);
|
|
||||||
if (offset > 0)
|
|
||||||
{
|
|
||||||
wchar_t range[64] = { 0 };
|
|
||||||
swprintf_s(range, L"Range: bytes=%lld-", offset);
|
|
||||||
::WinHttpAddRequestHeaders(request.get(), range, static_cast<DWORD>(-1),
|
|
||||||
WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!::WinHttpSendRequest(request.get(), WINHTTP_NO_ADDITIONAL_HEADERS, 0,
|
|
||||||
WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
|
|
||||||
{
|
|
||||||
error = L"请求发送失败:" + NetworkErrorText(::GetLastError());
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!::WinHttpReceiveResponse(request.get(), nullptr))
|
|
||||||
{
|
|
||||||
error = L"接收响应失败:" + NetworkErrorText(::GetLastError());
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
|
|
||||||
DWORD status = 0;
|
|
||||||
DWORD status_size = sizeof(status);
|
|
||||||
if (!::WinHttpQueryHeaders(request.get(), WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
|
|
||||||
WINHTTP_HEADER_NAME_BY_INDEX, &status, &status_size, WINHTTP_NO_HEADER_INDEX))
|
|
||||||
{
|
|
||||||
error = L"无法读取 HTTP 状态码";
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status == 416)
|
if (status == 416)
|
||||||
{
|
{
|
||||||
@@ -827,11 +670,10 @@ DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
|||||||
}
|
}
|
||||||
|
|
||||||
int64_t downloaded = status == 200 ? 0 : offset;
|
int64_t downloaded = status == 200 ? 0 : offset;
|
||||||
int64_t content_length = QueryContentLength(request.get());
|
int64_t content_length = response.content_length;
|
||||||
if (status == 206)
|
if (status == 206)
|
||||||
{
|
{
|
||||||
int64_t total = ParseContentRangeTotal(
|
int64_t total = ParseContentRangeTotal(response.content_range);
|
||||||
QueryHeaderText(request.get(), WINHTTP_QUERY_CONTENT_RANGE));
|
|
||||||
if (total > 0)
|
if (total > 0)
|
||||||
task.total_bytes = total;
|
task.total_bytes = total;
|
||||||
else if (content_length > 0)
|
else if (content_length > 0)
|
||||||
@@ -875,31 +717,21 @@ DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
|||||||
if (stop_ || cancel_current_)
|
if (stop_ || cancel_current_)
|
||||||
return AttemptResult::kCanceled;
|
return AttemptResult::kCanceled;
|
||||||
|
|
||||||
DWORD available = 0;
|
const auto chunk=stream->Read(buffer);
|
||||||
if (!::WinHttpQueryDataAvailable(request.get(), &available))
|
DrainCommands();
|
||||||
{
|
if (stop_ || cancel_current_) return AttemptResult::kCanceled;
|
||||||
DWORD code = ::GetLastError();
|
if (chunk.state==http::ReadState::kTimeout && ++idle_timeouts<5) continue;
|
||||||
if (code == ERROR_WINHTTP_TIMEOUT && ++idle_timeouts < 5)
|
if (chunk.state==http::ReadState::kTimeout || chunk.state==http::ReadState::kError) {
|
||||||
continue;
|
error=chunk.error;
|
||||||
error = code == ERROR_WINHTTP_TIMEOUT ? L"下载超时" : L"接收数据失败:" + NetworkErrorText(code);
|
return AttemptResult::kRetry;
|
||||||
return AttemptResult::kRetry;
|
}
|
||||||
}
|
if (chunk.state==http::ReadState::kEnd) break;
|
||||||
if (available == 0)
|
idle_timeouts=0;
|
||||||
break;
|
if (chunk.size==0 || chunk.size>buffer.size()) {
|
||||||
idle_timeouts = 0;
|
error=L"HTTP 传输层返回了无效的数据长度";
|
||||||
|
return AttemptResult::kFatal;
|
||||||
DWORD to_read = (std::min)(available, static_cast<DWORD>(buffer.size()));
|
}
|
||||||
DWORD read = 0;
|
const DWORD read=static_cast<DWORD>(chunk.size);
|
||||||
if (!::WinHttpReadData(request.get(), buffer.data(), to_read, &read))
|
|
||||||
{
|
|
||||||
DWORD code = ::GetLastError();
|
|
||||||
if (code == ERROR_WINHTTP_TIMEOUT && ++idle_timeouts < 5)
|
|
||||||
continue;
|
|
||||||
error = code == ERROR_WINHTTP_TIMEOUT ? L"下载超时" : L"读取数据失败:" + NetworkErrorText(code);
|
|
||||||
return AttemptResult::kRetry;
|
|
||||||
}
|
|
||||||
if (read == 0)
|
|
||||||
break;
|
|
||||||
|
|
||||||
DWORD written = 0;
|
DWORD written = 0;
|
||||||
if (!::WriteFile(file.get(), buffer.data(), read, &written, nullptr) || written != read)
|
if (!::WriteFile(file.get(), buffer.data(), read, &written, nullptr) || written != read)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
|
|
||||||
#include "task_store.h"
|
#include "task_store.h"
|
||||||
|
#include "http_transport.h"
|
||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
@@ -36,6 +37,7 @@ class DownloadEngine
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
explicit DownloadEngine(HWND notify_wnd);
|
explicit DownloadEngine(HWND notify_wnd);
|
||||||
|
DownloadEngine(HWND notify_wnd,std::unique_ptr<http::Transport> transport);
|
||||||
~DownloadEngine();
|
~DownloadEngine();
|
||||||
|
|
||||||
void Start();
|
void Start();
|
||||||
@@ -89,6 +91,7 @@ private:
|
|||||||
void PostRejected(const std::wstring& message);
|
void PostRejected(const std::wstring& message);
|
||||||
|
|
||||||
HWND notify_wnd_ = nullptr;
|
HWND notify_wnd_ = nullptr;
|
||||||
|
std::unique_ptr<http::Transport> transport_;
|
||||||
std::thread thread_;
|
std::thread thread_;
|
||||||
std::atomic<bool> stop_{ false };
|
std::atomic<bool> stop_{ false };
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#include "stdafx.h"
|
||||||
|
#include "http_transport.h"
|
||||||
|
#include "winhttp_transport.h"
|
||||||
|
namespace http {
|
||||||
|
std::unique_ptr<Transport> CreateDefaultTransport() { return CreateWinHttpTransport(); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace http {
|
||||||
|
struct UrlParts {
|
||||||
|
std::wstring host;
|
||||||
|
std::wstring path;
|
||||||
|
std::uint16_t port=0;
|
||||||
|
bool https=false;
|
||||||
|
};
|
||||||
|
struct Timeouts {
|
||||||
|
int resolve_ms=15000;
|
||||||
|
int connect_ms=15000;
|
||||||
|
int send_ms=15000;
|
||||||
|
int receive_ms=4000;
|
||||||
|
};
|
||||||
|
struct Request {
|
||||||
|
std::wstring url;
|
||||||
|
std::int64_t range_offset=0;
|
||||||
|
Timeouts timeouts;
|
||||||
|
};
|
||||||
|
struct Response {
|
||||||
|
unsigned status=0;
|
||||||
|
std::int64_t content_length=0; // Zero means absent/unknown or an empty body.
|
||||||
|
std::wstring content_range;
|
||||||
|
};
|
||||||
|
enum class ReadState { kData,kEnd,kTimeout,kError };
|
||||||
|
struct ReadResult {
|
||||||
|
ReadState state=ReadState::kEnd;
|
||||||
|
std::size_t size=0;
|
||||||
|
std::wstring error;
|
||||||
|
};
|
||||||
|
// A synchronous stream, exclusively used and destroyed by its calling worker.
|
||||||
|
// No task state, disk writes, retries, database access or UI callbacks belong here.
|
||||||
|
class ResponseStream {
|
||||||
|
public:
|
||||||
|
virtual ~ResponseStream()=default;
|
||||||
|
virtual const Response& Headers() const=0;
|
||||||
|
// kData always has 0 < size <= buffer.size(); kEnd is the only successful EOF.
|
||||||
|
virtual ReadResult Read(std::span<char> buffer)=0;
|
||||||
|
};
|
||||||
|
enum class OpenError { kNone,kInvalidRequest,kNetwork,kTimeout };
|
||||||
|
struct OpenResult {
|
||||||
|
std::unique_ptr<ResponseStream> stream;
|
||||||
|
OpenError kind=OpenError::kNone;
|
||||||
|
std::wstring error;
|
||||||
|
};
|
||||||
|
class Transport {
|
||||||
|
public:
|
||||||
|
virtual ~Transport()=default;
|
||||||
|
virtual bool ParseUrl(const std::wstring& url,UrlParts& parts) const=0;
|
||||||
|
// HTTP errors such as 404/416 still return a stream and status; policy is up to the caller.
|
||||||
|
virtual OpenResult Open(const Request& request)=0;
|
||||||
|
};
|
||||||
|
// Composition point: currently WinHTTP. Constructors/factories do no network I/O.
|
||||||
|
std::unique_ptr<Transport> CreateDefaultTransport();
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
#include "stdafx.h"
|
||||||
|
#include "winhttp_transport.h"
|
||||||
|
#include <winhttp.h>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <limits>
|
||||||
|
#include <utility>
|
||||||
|
#pragma comment(lib,"winhttp.lib")
|
||||||
|
namespace http {
|
||||||
|
namespace {
|
||||||
|
using Handle=std::unique_ptr<void,decltype(&::WinHttpCloseHandle)>;
|
||||||
|
bool ParseWinHttpUrl(const std::wstring& url, UrlParts& parts)
|
||||||
|
{
|
||||||
|
URL_COMPONENTS components = {};
|
||||||
|
components.dwStructSize = sizeof(components);
|
||||||
|
components.dwSchemeLength = static_cast<DWORD>(-1);
|
||||||
|
components.dwHostNameLength = static_cast<DWORD>(-1);
|
||||||
|
components.dwUrlPathLength = static_cast<DWORD>(-1);
|
||||||
|
components.dwExtraInfoLength = static_cast<DWORD>(-1);
|
||||||
|
|
||||||
|
if (!::WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &components))
|
||||||
|
return false;
|
||||||
|
if (components.nScheme != INTERNET_SCHEME_HTTP && components.nScheme != INTERNET_SCHEME_HTTPS)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
parts.host.assign(components.lpszHostName, components.dwHostNameLength);
|
||||||
|
parts.path.assign(components.lpszUrlPath, components.dwUrlPathLength);
|
||||||
|
if (components.lpszExtraInfo != nullptr && components.dwExtraInfoLength > 0)
|
||||||
|
parts.path.append(components.lpszExtraInfo, components.dwExtraInfoLength);
|
||||||
|
if (parts.path.empty())
|
||||||
|
parts.path = L"/";
|
||||||
|
parts.port = components.nPort;
|
||||||
|
parts.https = components.nScheme == INTERNET_SCHEME_HTTPS;
|
||||||
|
return !parts.host.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::wstring NetworkErrorText(DWORD code)
|
||||||
|
{
|
||||||
|
wchar_t* buffer = nullptr;
|
||||||
|
DWORD length = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
|
||||||
|
| FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, code, 0,
|
||||||
|
reinterpret_cast<wchar_t*>(&buffer), 0, nullptr);
|
||||||
|
if (length == 0 || buffer == nullptr)
|
||||||
|
{
|
||||||
|
HMODULE winhttp = ::GetModuleHandleW(L"winhttp.dll");
|
||||||
|
if (winhttp != nullptr)
|
||||||
|
{
|
||||||
|
length = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE
|
||||||
|
| FORMAT_MESSAGE_IGNORE_INSERTS, winhttp, code, 0,
|
||||||
|
reinterpret_cast<wchar_t*>(&buffer), 0, nullptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length == 0 || buffer == nullptr)
|
||||||
|
{
|
||||||
|
wchar_t fallback[32] = { 0 };
|
||||||
|
swprintf_s(fallback, L"错误码 %u", code);
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::wstring text(buffer, length);
|
||||||
|
::LocalFree(buffer);
|
||||||
|
while (!text.empty() && (text.back() == L'\r' || text.back() == L'\n' || text.back() == L' '))
|
||||||
|
text.pop_back();
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::wstring QueryHeaderText(HINTERNET request, DWORD query);
|
||||||
|
int64_t QueryContentLength(HINTERNET request) {
|
||||||
|
const std::wstring text=QueryHeaderText(request,WINHTTP_QUERY_CONTENT_LENGTH);
|
||||||
|
if (text.empty()) return 0;
|
||||||
|
int64_t value=0;
|
||||||
|
for (wchar_t ch:text) {
|
||||||
|
if (ch<L'0' || ch>L'9' || value>(INT64_MAX-(ch-L'0'))/10) return 0;
|
||||||
|
value=value*10+(ch-L'0');
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::wstring QueryHeaderText(HINTERNET request, DWORD query)
|
||||||
|
{
|
||||||
|
DWORD size = 0;
|
||||||
|
::WinHttpQueryHeaders(request, query, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||||
|
WINHTTP_NO_OUTPUT_BUFFER, &size, WINHTTP_NO_HEADER_INDEX);
|
||||||
|
if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER || size == 0)
|
||||||
|
return std::wstring();
|
||||||
|
|
||||||
|
std::wstring text(size / sizeof(wchar_t), L'\0');
|
||||||
|
if (!::WinHttpQueryHeaders(request, query, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||||
|
text.data(), &size, WINHTTP_NO_HEADER_INDEX))
|
||||||
|
return std::wstring();
|
||||||
|
|
||||||
|
text.resize(size / sizeof(wchar_t));
|
||||||
|
while (!text.empty() && text.back() == L'\0')
|
||||||
|
text.pop_back();
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
ReadResult ReadError(DWORD code,const wchar_t* prefix) {
|
||||||
|
if (code==ERROR_WINHTTP_TIMEOUT) return {ReadState::kTimeout,0,L"下载超时"};
|
||||||
|
return {ReadState::kError,0,std::wstring(prefix)+NetworkErrorText(code)};
|
||||||
|
}
|
||||||
|
class WinHttpStream final : public ResponseStream {
|
||||||
|
public:
|
||||||
|
WinHttpStream(Handle session,Handle connection,Handle request,Response headers)
|
||||||
|
:session_(std::move(session)),connection_(std::move(connection)),request_(std::move(request)),headers_(std::move(headers)) {}
|
||||||
|
const Response& Headers() const override { return headers_; }
|
||||||
|
ReadResult Read(std::span<char> buffer) override {
|
||||||
|
if (buffer.empty()) return {ReadState::kError,0,L"读取缓冲区不能为空"};
|
||||||
|
DWORD count=static_cast<DWORD>(std::min<std::size_t>(buffer.size(),(std::numeric_limits<DWORD>::max)()));
|
||||||
|
DWORD read=0;
|
||||||
|
if (!WinHttpReadData(request_.get(),buffer.data(),count,&read)) return ReadError(GetLastError(),L"读取数据失败:");
|
||||||
|
if (read==0) return {ReadState::kEnd,0,{}};
|
||||||
|
return {ReadState::kData,read,{}};
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
Handle session_,connection_,request_;
|
||||||
|
Response headers_;
|
||||||
|
};
|
||||||
|
OpenResult Failure(const wchar_t* prefix,DWORD code) {
|
||||||
|
return {nullptr,code==ERROR_WINHTTP_TIMEOUT?OpenError::kTimeout:OpenError::kNetwork,std::wstring(prefix)+NetworkErrorText(code)};
|
||||||
|
}
|
||||||
|
class WinHttpTransport final : public Transport {
|
||||||
|
public:
|
||||||
|
bool ParseUrl(const std::wstring& url,UrlParts& parts) const override { return ParseWinHttpUrl(url,parts); }
|
||||||
|
OpenResult Open(const Request& input) override {
|
||||||
|
UrlParts parts;
|
||||||
|
if (input.range_offset<0 || !ParseUrl(input.url,parts)) return {nullptr,OpenError::kInvalidRequest,L"无效的下载链接或续传偏移"};
|
||||||
|
const auto& timeout=input.timeouts;
|
||||||
|
if (timeout.resolve_ms<=0 || timeout.connect_ms<=0 || timeout.send_ms<=0 || timeout.receive_ms<=0)
|
||||||
|
return {nullptr,OpenError::kInvalidRequest,L"网络超时必须大于零"};
|
||||||
|
Handle session(WinHttpOpen(L"TTDownloader/0.1",WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
||||||
|
WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0),&::WinHttpCloseHandle);
|
||||||
|
const bool legacy_proxy=!session && GetLastError()==ERROR_INVALID_PARAMETER;
|
||||||
|
if (legacy_proxy) session.reset(WinHttpOpen(L"TTDownloader/0.1",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
|
||||||
|
WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0));
|
||||||
|
if (!session) return Failure(L"无法初始化网络连接:",GetLastError());
|
||||||
|
if (legacy_proxy) {
|
||||||
|
DWORD protocols=WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
|
||||||
|
WinHttpSetOption(session.get(),WINHTTP_OPTION_SECURE_PROTOCOLS,&protocols,sizeof(protocols));
|
||||||
|
}
|
||||||
|
if (!WinHttpSetTimeouts(session.get(),timeout.resolve_ms,timeout.connect_ms,timeout.send_ms,timeout.receive_ms))
|
||||||
|
return Failure(L"无法设置网络超时:",GetLastError());
|
||||||
|
Handle connection(WinHttpConnect(session.get(),parts.host.c_str(),parts.port,0),&::WinHttpCloseHandle);
|
||||||
|
if (!connection) return Failure(L"无法连接服务器:",GetLastError());
|
||||||
|
Handle request(WinHttpOpenRequest(connection.get(),L"GET",parts.path.c_str(),nullptr,WINHTTP_NO_REFERER,
|
||||||
|
WINHTTP_DEFAULT_ACCEPT_TYPES,parts.https?WINHTTP_FLAG_SECURE:0),&::WinHttpCloseHandle);
|
||||||
|
if (!request) return Failure(L"无法创建下载请求:",GetLastError());
|
||||||
|
if (!WinHttpSetTimeouts(request.get(),timeout.resolve_ms,timeout.connect_ms,timeout.send_ms,timeout.receive_ms))
|
||||||
|
return Failure(L"无法设置请求超时:",GetLastError());
|
||||||
|
if (input.range_offset>0) {
|
||||||
|
const std::wstring range=L"Range: bytes="+std::to_wstring(input.range_offset)+L"-";
|
||||||
|
if (!WinHttpAddRequestHeaders(request.get(),range.c_str(),static_cast<DWORD>(-1),WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_REPLACE))
|
||||||
|
return Failure(L"无法设置续传请求:",GetLastError());
|
||||||
|
}
|
||||||
|
if (!WinHttpSendRequest(request.get(),WINHTTP_NO_ADDITIONAL_HEADERS,0,WINHTTP_NO_REQUEST_DATA,0,0,0))
|
||||||
|
return Failure(L"请求发送失败:",GetLastError());
|
||||||
|
if (!WinHttpReceiveResponse(request.get(),nullptr)) return Failure(L"接收响应失败:",GetLastError());
|
||||||
|
DWORD status=0,size=sizeof(status);
|
||||||
|
if (!WinHttpQueryHeaders(request.get(),WINHTTP_QUERY_STATUS_CODE|WINHTTP_QUERY_FLAG_NUMBER,
|
||||||
|
WINHTTP_HEADER_NAME_BY_INDEX,&status,&size,WINHTTP_NO_HEADER_INDEX))
|
||||||
|
return Failure(L"无法读取 HTTP 状态码:",GetLastError());
|
||||||
|
Response headers{status,QueryContentLength(request.get()),QueryHeaderText(request.get(),WINHTTP_QUERY_CONTENT_RANGE)};
|
||||||
|
OpenResult result;
|
||||||
|
result.stream=std::make_unique<WinHttpStream>(std::move(session),std::move(connection),std::move(request),std::move(headers));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
std::unique_ptr<Transport> CreateWinHttpTransport() { return std::make_unique<WinHttpTransport>(); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "http_transport.h"
|
||||||
|
namespace http {
|
||||||
|
std::unique_ptr<Transport> CreateWinHttpTransport();
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
#include "http_transport.h"
|
||||||
|
#include <future>
|
||||||
|
#include <chrono>
|
||||||
|
#include <array>
|
||||||
|
#include <iostream>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <vector>
|
||||||
|
static void Check(bool value,const char* message) { if (!value) throw std::runtime_error(message); }
|
||||||
|
static std::vector<char> Drain(http::ResponseStream& stream) {
|
||||||
|
std::vector<char> body;
|
||||||
|
std::array<char,997> buffer{};
|
||||||
|
for (int iteration=0;iteration<10000;++iteration) {
|
||||||
|
auto result=stream.Read(buffer);
|
||||||
|
if (result.state==http::ReadState::kEnd) return body;
|
||||||
|
Check(result.state==http::ReadState::kData && result.size>0 && result.size<=buffer.size(),"bounded stream read");
|
||||||
|
body.insert(body.end(),buffer.begin(),buffer.begin()+result.size);
|
||||||
|
}
|
||||||
|
throw std::runtime_error("stream did not reach EOF");
|
||||||
|
}
|
||||||
|
static void Run(const std::wstring& base) {
|
||||||
|
auto transport=http::CreateDefaultTransport();
|
||||||
|
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");
|
||||||
|
std::vector<char> payload;
|
||||||
|
for (int i=0;i<256*257;++i) payload.push_back(static_cast<char>(i%256));
|
||||||
|
const std::string tail="TTDownloader-http"; payload.insert(payload.end(),tail.begin(),tail.end());
|
||||||
|
auto open=[&](const wchar_t* path,long long offset=0) {
|
||||||
|
http::Request request; request.url=base+path; request.range_offset=offset;
|
||||||
|
auto result=transport->Open(request);
|
||||||
|
Check(result.stream!=nullptr && result.kind==http::OpenError::kNone,"open loopback HTTP response");
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
{
|
||||||
|
auto response=open(L"/plain");
|
||||||
|
Check(response.stream->Headers().status==200 && response.stream->Headers().content_length==payload.size(),"full response headers");
|
||||||
|
Check(Drain(*response.stream)==payload,"binary response bytes");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
auto response=open(L"/range?x=1",123);
|
||||||
|
const auto& headers=response.stream->Headers();
|
||||||
|
Check(headers.status==206 && headers.content_length==payload.size()-123
|
||||||
|
&& headers.content_range==L"bytes 123-"+std::to_wstring(payload.size()-1)+L"/"+std::to_wstring(payload.size()),"range request and raw metadata");
|
||||||
|
Check(Drain(*response.stream)==std::vector<char>(payload.begin()+123,payload.end()),"range response bytes");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
auto response=open(L"/ignore-range",123);
|
||||||
|
Check(response.stream->Headers().status==200 && Drain(*response.stream)==payload,"surface ignored Range as 200 without transport retry");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
auto response=open(L"/unsatisfiable",123);
|
||||||
|
Check(response.stream->Headers().status==416 && response.stream->Headers().content_range==L"bytes */"+std::to_wstring(payload.size()),"surface 416 without deleting files or restarting");
|
||||||
|
Check(Drain(*response.stream).empty(),"empty HTTP error response");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
auto response=open(L"/missing");
|
||||||
|
Check(response.stream->Headers().status==404,"HTTP error is a response, not a network failure");
|
||||||
|
Check(!Drain(*response.stream).empty(),"HTTP error body available to caller");
|
||||||
|
}
|
||||||
|
{ auto response=open(L"/redirect"); Check(response.stream->Headers().status==200 && Drain(*response.stream)==payload,"follow redirects"); }
|
||||||
|
{ auto response=open(L"/chunked"); Check(response.stream->Headers().content_length==0 && Drain(*response.stream)==payload,"chunked response and unknown content length"); }
|
||||||
|
{ auto response=open(L"/large-length"); Check(response.stream->Headers().content_length==5368709120LL,"64-bit Content-Length on legacy-compatible query path"); }
|
||||||
|
{ auto response=open(L"/overflow-length"); Check(response.stream->Headers().content_length==0,"overflowed Content-Length is unknown"); }
|
||||||
|
{
|
||||||
|
http::Request request; request.url=base+L"/slow"; request.timeouts.receive_ms=100;
|
||||||
|
auto started=std::chrono::steady_clock::now();
|
||||||
|
auto response=transport->Open(request); Check(response.stream!=nullptr,"slow response headers received");
|
||||||
|
auto opened=std::chrono::steady_clock::now();
|
||||||
|
std::array<char,16> buffer{}; auto result=response.stream->Read(buffer);
|
||||||
|
if (result.state!=http::ReadState::kTimeout) std::cerr<<"Slow test diagnostic: open_ms="<<std::chrono::duration_cast<std::chrono::milliseconds>(opened-started).count()
|
||||||
|
<<" read_ms="<<std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-opened).count()<<" state="<<static_cast<int>(result.state)<<" bytes="<<result.size<<"\n";
|
||||||
|
Check(result.state==http::ReadState::kTimeout && !result.error.empty(),"timeouts are reported for scheduler policy");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
auto response=open(L"/plain");
|
||||||
|
Check(response.stream->Read({}).state==http::ReadState::kError,"empty read buffer is not mistaken for EOF");
|
||||||
|
Check(Drain(*response.stream)==payload,"invalid read does not consume data");
|
||||||
|
}
|
||||||
|
http::Request invalid; invalid.url=L"ftp://example.test/file";
|
||||||
|
Check(transport->Open(invalid).kind==http::OpenError::kInvalidRequest,"invalid URL classification");
|
||||||
|
invalid.url=base+L"/plain"; invalid.range_offset=-1;
|
||||||
|
Check(transport->Open(invalid).kind==http::OpenError::kInvalidRequest,"negative range offset classification");
|
||||||
|
invalid.range_offset=0; invalid.timeouts.receive_ms=0;
|
||||||
|
Check(transport->Open(invalid).kind==http::OpenError::kInvalidRequest,"reject unbounded timeout configuration");
|
||||||
|
}
|
||||||
|
int wmain(int argc,wchar_t** argv) {
|
||||||
|
if (argc!=2) { std::cerr<<"Expected loopback server URL\n"; return 2; }
|
||||||
|
try {
|
||||||
|
// 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";
|
||||||
|
return 0;
|
||||||
|
} catch (const std::exception& error) { std::cerr<<"FAIL: "<<error.what()<<"\n"; return 1; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||||
|
<ItemGroup Label="ProjectConfigurations">
|
||||||
|
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
|
||||||
|
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform></ProjectConfiguration>
|
||||||
|
</ItemGroup>
|
||||||
|
<PropertyGroup Label="Globals"><ProjectGuid>{8B5E30AF-6704-4CDE-A16B-16EBC7F88522}</ProjectGuid><VcpkgEnabled>false</VcpkgEnabled></PropertyGroup>
|
||||||
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||||
|
<PropertyGroup Label="Configuration"><ConfigurationType>Application</ConfigurationType><PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet></PropertyGroup>
|
||||||
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||||
|
<PropertyGroup><OutDir>$(ProjectDir)..\bin\tests\$(Configuration)\</OutDir><IntDir>$(ProjectDir)..\obj\http_tests\$(Configuration)\</IntDir></PropertyGroup>
|
||||||
|
<ItemDefinitionGroup>
|
||||||
|
<ClCompile>
|
||||||
|
<LanguageStandard>stdcpp20</LanguageStandard><AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions><ExceptionHandling>Sync</ExceptionHandling>
|
||||||
|
<PreprocessorDefinitions>NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||||
|
<AdditionalIncludeDirectories>$(ProjectDir)..\src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||||
|
<RuntimeLibrary Condition="'$(Configuration)'=='Debug'">MultiThreadedDebug</RuntimeLibrary>
|
||||||
|
<RuntimeLibrary Condition="'$(Configuration)'=='Release'">MultiThreaded</RuntimeLibrary>
|
||||||
|
</ClCompile>
|
||||||
|
<Link><SubSystem>Console</SubSystem><MinimumRequiredVersion>6.01</MinimumRequiredVersion></Link>
|
||||||
|
</ItemDefinitionGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ClCompile Include="http_transport_tests.cpp" />
|
||||||
|
<ClCompile Include="..\src\http_transport.cpp" />
|
||||||
|
<ClCompile Include="..\src\winhttp_transport.cpp" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""Run transport tests against an ephemeral loopback-only HTTP server."""
|
||||||
|
import http.server
|
||||||
|
import pathlib
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
PAYLOAD = bytes(range(256)) * 257 + b"TTDownloader-http"
|
||||||
|
|
||||||
|
class Handler(http.server.BaseHTTPRequestHandler):
|
||||||
|
protocol_version = "HTTP/1.1"
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
def do_GET(self):
|
||||||
|
path = urllib.parse.urlsplit(self.path).path
|
||||||
|
if path == "/redirect":
|
||||||
|
self.send_response(302)
|
||||||
|
self.send_header("Location", "/plain")
|
||||||
|
self.send_header("Content-Length", "0")
|
||||||
|
self.end_headers()
|
||||||
|
return
|
||||||
|
if path == "/chunked":
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Transfer-Encoding", "chunked")
|
||||||
|
self.end_headers()
|
||||||
|
for offset in range(0, len(PAYLOAD), 1021):
|
||||||
|
chunk = PAYLOAD[offset:offset+1021]
|
||||||
|
self.wfile.write(("%x\r\n" % len(chunk)).encode("ascii") + chunk + b"\r\n")
|
||||||
|
self.wfile.write(b"0\r\n\r\n")
|
||||||
|
return
|
||||||
|
if path in ("/large-length", "/overflow-length"):
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Length", "5368709120" if path == "/large-length" else "9223372036854775808")
|
||||||
|
self.send_header("Connection", "close")
|
||||||
|
self.end_headers()
|
||||||
|
self.close_connection = True
|
||||||
|
return
|
||||||
|
if path == "/slow":
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Length", "1")
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.flush()
|
||||||
|
# Leave enough margin for WinHTTP's coarse timeout polling.
|
||||||
|
time.sleep(8)
|
||||||
|
try:
|
||||||
|
self.wfile.write(b"x")
|
||||||
|
except (BrokenPipeError, ConnectionResetError):
|
||||||
|
pass
|
||||||
|
return
|
||||||
|
body = PAYLOAD
|
||||||
|
code = 200
|
||||||
|
content_range = None
|
||||||
|
if path == "/range":
|
||||||
|
if self.headers.get("Range") != "bytes=123-":
|
||||||
|
code, body = 400, b"wrong range"
|
||||||
|
else:
|
||||||
|
code, body = 206, PAYLOAD[123:]
|
||||||
|
content_range = "bytes 123-%d/%d" % (len(PAYLOAD)-1, len(PAYLOAD))
|
||||||
|
elif path == "/unsatisfiable":
|
||||||
|
code, body = 416, b""
|
||||||
|
content_range = "bytes */%d" % len(PAYLOAD)
|
||||||
|
elif path not in ("/plain", "/ignore-range"):
|
||||||
|
code, body = 404, b"missing"
|
||||||
|
self.send_response(code)
|
||||||
|
if content_range:
|
||||||
|
self.send_header("Content-Range", content_range)
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
try:
|
||||||
|
self.wfile.write(body)
|
||||||
|
except (BrokenPipeError, ConnectionResetError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Server(http.server.ThreadingHTTPServer):
|
||||||
|
daemon_threads = True
|
||||||
|
def handle_error(self, request, address):
|
||||||
|
# Closing an unread stream is part of the test, so connection resets are expected.
|
||||||
|
pass
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
binary = pathlib.Path(sys.argv[1]).resolve()
|
||||||
|
server = Server(("127.0.0.1", 0), Handler)
|
||||||
|
worker = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
worker.start()
|
||||||
|
try:
|
||||||
|
result = subprocess.run([str(binary), "http://127.0.0.1:%d" % server.server_port], timeout=40)
|
||||||
|
code = result.returncode
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
worker.join()
|
||||||
|
sys.exit(code)
|
||||||
@@ -101,6 +101,8 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ClInclude Include="src\add_task_form.h" />
|
<ClInclude Include="src\add_task_form.h" />
|
||||||
<ClInclude Include="src\download_engine.h" />
|
<ClInclude Include="src\download_engine.h" />
|
||||||
|
<ClInclude Include="src\http_transport.h" />
|
||||||
|
<ClInclude Include="src\winhttp_transport.h" />
|
||||||
<ClInclude Include="src\downloader_form.h" />
|
<ClInclude Include="src\downloader_form.h" />
|
||||||
<ClInclude Include="src\file_drop_source.h" />
|
<ClInclude Include="src\file_drop_source.h" />
|
||||||
<ClInclude Include="src\settings_form.h" />
|
<ClInclude Include="src\settings_form.h" />
|
||||||
@@ -112,6 +114,8 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ClCompile Include="src\add_task_form.cpp" />
|
<ClCompile Include="src\add_task_form.cpp" />
|
||||||
<ClCompile Include="src\download_engine.cpp" />
|
<ClCompile Include="src\download_engine.cpp" />
|
||||||
|
<ClCompile Include="src\http_transport.cpp" />
|
||||||
|
<ClCompile Include="src\winhttp_transport.cpp" />
|
||||||
<ClCompile Include="src\downloader_form.cpp" />
|
<ClCompile Include="src\downloader_form.cpp" />
|
||||||
<ClCompile Include="src\file_drop_source.cpp" />
|
<ClCompile Include="src\file_drop_source.cpp" />
|
||||||
<ClCompile Include="src\main.cpp" />
|
<ClCompile Include="src\main.cpp" />
|
||||||
|
|||||||
@@ -9,8 +9,15 @@ if not defined TTUI_MSBUILD (
|
|||||||
)
|
)
|
||||||
"%TTUI_MSBUILD%" "%~dp0ui\ttui\tests\smoke.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal
|
"%TTUI_MSBUILD%" "%~dp0ui\ttui\tests\smoke.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal
|
||||||
if errorlevel 1 exit /b 1
|
if errorlevel 1 exit /b 1
|
||||||
|
"%TTUI_MSBUILD%" "%~dp0client\tests\http_transport_tests.vcxproj" -p:Configuration=%TTUI_TEST_CONFIG% -p:Platform=x64 -v:minimal
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
pushd "%~dp0"
|
pushd "%~dp0"
|
||||||
"%~dp0ui\ttui\lib\x64\%TTUI_TEST_CONFIG%\smoke.exe"
|
"%~dp0ui\ttui\lib\x64\%TTUI_TEST_CONFIG%\smoke.exe"
|
||||||
|
if errorlevel 1 (
|
||||||
|
popd
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
python "%~dp0client\tests\run_http_transport_tests.py" "%~dp0client\bin\tests\%TTUI_TEST_CONFIG%\http_transport_tests.exe"
|
||||||
set "TTUI_TEST_EXIT=%ERRORLEVEL%"
|
set "TTUI_TEST_EXIT=%ERRORLEVEL%"
|
||||||
popd
|
popd
|
||||||
endlocal & exit /b %TTUI_TEST_EXIT%
|
endlocal & exit /b %TTUI_TEST_EXIT%
|
||||||
Reference in new issue
Block a user