分离 HTTP 传输接口与下载任务调度
封装 WinHTTP 请求和响应流,保留任务引擎中的续传、文件写入、重试与持久化策略。增加本地 HTTP 契约测试和后端替换说明。
This commit is contained in:
1 parent
db38ec5c03
commit
6c810c3b4f
13 files changed
+551
-208
No files matched your search
+40
-208
@@ -2,27 +2,14 @@
|
||||
#include "platform.h"
|
||||
#include "download_engine.h"
|
||||
|
||||
#include <winhttp.h>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cwctype>
|
||||
|
||||
#pragma comment(lib, "winhttp.lib")
|
||||
|
||||
namespace
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct UrlParts
|
||||
{
|
||||
std::wstring host;
|
||||
std::wstring path;
|
||||
INTERNET_PORT port = 0;
|
||||
bool https = false;
|
||||
};
|
||||
}
|
||||
|
||||
std::wstring Trim(const std::wstring& text)
|
||||
{
|
||||
size_t begin = 0;
|
||||
@@ -68,31 +55,6 @@ namespace
|
||||
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)
|
||||
{
|
||||
if (c >= L'0' && c <= L'9')
|
||||
@@ -167,11 +129,11 @@ namespace
|
||||
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;
|
||||
if (CrackUrl(url, parts))
|
||||
if (transport.ParseUrl(url, parts))
|
||||
path = parts.path;
|
||||
|
||||
size_t query = path.find_first_of(L"?#");
|
||||
@@ -240,68 +202,6 @@ namespace
|
||||
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)
|
||||
{
|
||||
size_t slash = value.find_last_of(L'/');
|
||||
@@ -315,8 +215,11 @@ namespace
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -420,7 +323,7 @@ void DownloadEngine::ThreadMain()
|
||||
if (task.file_name.empty())
|
||||
{
|
||||
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_);
|
||||
store_.UpdateTarget(task.id, task.save_path, task.file_name);
|
||||
}
|
||||
@@ -527,8 +430,8 @@ void DownloadEngine::HandleAdd(const Command& cmd)
|
||||
return;
|
||||
}
|
||||
|
||||
UrlParts parts;
|
||||
if (!CrackUrl(url, parts))
|
||||
http::UrlParts parts;
|
||||
if (!transport_->ParseUrl(url, parts))
|
||||
{
|
||||
PostRejected(L"仅支持有效的 HTTP/HTTPS 链接");
|
||||
return;
|
||||
@@ -556,7 +459,7 @@ void DownloadEngine::HandleAdd(const Command& cmd)
|
||||
|
||||
TaskInfo task;
|
||||
task.url = url;
|
||||
task.file_name = FileNameFromUrl(url);
|
||||
task.file_name = FileNameFromUrl(url,*transport_);
|
||||
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
||||
task.state = TaskState::kQueued;
|
||||
|
||||
@@ -737,78 +640,18 @@ void DownloadEngine::Download(TaskInfo& task)
|
||||
DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
||||
const std::wstring& part_path, std::wstring& error)
|
||||
{
|
||||
UrlParts parts;
|
||||
if (!CrackUrl(task.url, parts))
|
||||
{
|
||||
error = L"无效的下载链接";
|
||||
return AttemptResult::kFatal;
|
||||
}
|
||||
|
||||
using WinHttpHandle = std::unique_ptr<void, decltype(&::WinHttpCloseHandle)>;
|
||||
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));
|
||||
const int64_t offset=GetFileSize(part_path);
|
||||
http::Request request;
|
||||
request.url=task.url;
|
||||
request.range_offset=offset;
|
||||
auto opened=transport_->Open(request);
|
||||
if (!opened.stream) {
|
||||
error=opened.error;
|
||||
return opened.kind==http::OpenError::kInvalidRequest?AttemptResult::kFatal:AttemptResult::kRetry;
|
||||
}
|
||||
::WinHttpSetTimeouts(session.get(), 15000, 15000, 15000, 4000);
|
||||
|
||||
WinHttpHandle connect(::WinHttpConnect(session.get(), parts.host.c_str(), parts.port, 0),
|
||||
&::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;
|
||||
}
|
||||
auto stream=std::move(opened.stream);
|
||||
const auto& response=stream->Headers();
|
||||
const unsigned status=response.status;
|
||||
|
||||
if (status == 416)
|
||||
{
|
||||
@@ -827,11 +670,10 @@ DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
||||
}
|
||||
|
||||
int64_t downloaded = status == 200 ? 0 : offset;
|
||||
int64_t content_length = QueryContentLength(request.get());
|
||||
int64_t content_length = response.content_length;
|
||||
if (status == 206)
|
||||
{
|
||||
int64_t total = ParseContentRangeTotal(
|
||||
QueryHeaderText(request.get(), WINHTTP_QUERY_CONTENT_RANGE));
|
||||
int64_t total = ParseContentRangeTotal(response.content_range);
|
||||
if (total > 0)
|
||||
task.total_bytes = total;
|
||||
else if (content_length > 0)
|
||||
@@ -875,31 +717,21 @@ DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
||||
if (stop_ || cancel_current_)
|
||||
return AttemptResult::kCanceled;
|
||||
|
||||
DWORD available = 0;
|
||||
if (!::WinHttpQueryDataAvailable(request.get(), &available))
|
||||
{
|
||||
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 (available == 0)
|
||||
break;
|
||||
idle_timeouts = 0;
|
||||
|
||||
DWORD to_read = (std::min)(available, static_cast<DWORD>(buffer.size()));
|
||||
DWORD read = 0;
|
||||
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;
|
||||
const auto chunk=stream->Read(buffer);
|
||||
DrainCommands();
|
||||
if (stop_ || cancel_current_) return AttemptResult::kCanceled;
|
||||
if (chunk.state==http::ReadState::kTimeout && ++idle_timeouts<5) continue;
|
||||
if (chunk.state==http::ReadState::kTimeout || chunk.state==http::ReadState::kError) {
|
||||
error=chunk.error;
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
if (chunk.state==http::ReadState::kEnd) break;
|
||||
idle_timeouts=0;
|
||||
if (chunk.size==0 || chunk.size>buffer.size()) {
|
||||
error=L"HTTP 传输层返回了无效的数据长度";
|
||||
return AttemptResult::kFatal;
|
||||
}
|
||||
const DWORD read=static_cast<DWORD>(chunk.size);
|
||||
|
||||
DWORD written = 0;
|
||||
if (!::WriteFile(file.get(), buffer.data(), read, &written, nullptr) || written != read)
|
||||
|
||||
Reference in new issue
Block a user