Files

254 lines
9.2 KiB
C++
Raw Permalink Normal View History

#include "Http.h"
#include <winhttp.h>
#include <string>
#include <vector>
#pragma comment(lib, "winhttp.lib")
namespace updater {
int Http::timeoutSec_ = 30;
namespace {
struct UrlParts {
std::wstring host;
std::wstring path;
INTERNET_PORT port = INTERNET_DEFAULT_HTTP_PORT;
bool https = false;
};
bool CrackUrl(const std::wstring& url, UrlParts& out) {
URL_COMPONENTS uc;
ZeroMemory(&uc, sizeof(uc));
uc.dwStructSize = sizeof(uc);
uc.dwSchemeLength = static_cast<DWORD>(-1);
uc.dwHostNameLength = static_cast<DWORD>(-1);
uc.dwUrlPathLength = static_cast<DWORD>(-1);
uc.dwExtraInfoLength = static_cast<DWORD>(-1);
if (!WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &uc)) return false;
out.host.assign(uc.lpszHostName, uc.dwHostNameLength);
out.path.assign(uc.lpszUrlPath, uc.dwUrlPathLength);
if (uc.dwExtraInfoLength > 0 && uc.lpszExtraInfo) {
out.path.append(uc.lpszExtraInfo, uc.dwExtraInfoLength);
}
if (out.path.empty()) out.path = L"/";
out.port = uc.nPort;
out.https = uc.nScheme == INTERNET_SCHEME_HTTPS;
return true;
}
std::wstring ResolveUrl(const std::wstring& base, const std::wstring& location) {
if (location.empty()) return std::wstring();
if (_wcsnicmp(location.c_str(), L"http://", 7) == 0 ||
_wcsnicmp(location.c_str(), L"https://", 8) == 0) {
return location;
}
UrlParts parts;
if (!CrackUrl(base, parts)) return location;
std::wstring scheme = parts.https ? L"https://" : L"http://";
std::wstring hostPort = parts.host;
if ((parts.https && parts.port != INTERNET_DEFAULT_HTTPS_PORT) ||
(!parts.https && parts.port != INTERNET_DEFAULT_HTTP_PORT)) {
hostPort += L":" + std::to_wstring(parts.port);
}
if (location[0] == L'/') return scheme + hostPort + location;
std::wstring dir = parts.path;
size_t pos = dir.find_last_of(L'/');
if (pos == std::wstring::npos) dir = L"/";
else dir = dir.substr(0, pos + 1);
return scheme + hostPort + dir + location;
}
class Session {
public:
Session() {
DWORD access = WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
hSession_ = WinHttpOpen(L"Updater/1.0", access, WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
}
~Session() {
if (hSession_) WinHttpCloseHandle(hSession_);
}
bool valid() const { return hSession_ != nullptr; }
HINTERNET get() const { return hSession_; }
private:
HINTERNET hSession_ = nullptr;
};
class Request {
public:
Request(HINTERNET session, const std::wstring& url, bool download) {
if (!CrackUrl(url, parts_)) return;
hConnect_ = WinHttpConnect(session, parts_.host.c_str(), parts_.port, 0);
if (!hConnect_) return;
DWORD flags = parts_.https ? WINHTTP_FLAG_SECURE : 0;
hRequest_ = WinHttpOpenRequest(hConnect_, L"GET", parts_.path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags);
if (!hRequest_) return;
WinHttpSetTimeouts(hRequest_, Http::TimeoutMs(), Http::TimeoutMs(),
Http::TimeoutMs(), Http::TimeoutMs());
if (!download) {
DWORD disable = WINHTTP_DISABLE_COOKIES;
WinHttpSetOption(hRequest_, WINHTTP_OPTION_DISABLE_FEATURE, &disable,
sizeof(disable));
}
opened_ = true;
}
~Request() {
if (hRequest_) WinHttpCloseHandle(hRequest_);
if (hConnect_) WinHttpCloseHandle(hConnect_);
}
bool opened() const { return opened_; }
bool Send() {
return WinHttpSendRequest(hRequest_, WINHTTP_NO_REQUEST_DATA, 0,
WINHTTP_NO_REQUEST_DATA, 0, 0, 0) != FALSE &&
WinHttpReceiveResponse(hRequest_, nullptr) != FALSE;
}
long Status() {
DWORD code = 0;
DWORD size = sizeof(code);
if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &code, &size,
WINHTTP_NO_HEADER_INDEX)) {
return static_cast<long>(code);
}
return 0;
}
std::wstring Location() {
wchar_t buf[4096] = {0};
DWORD size = sizeof(buf);
if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX,
buf, &size, WINHTTP_NO_HEADER_INDEX)) {
return std::wstring(buf);
}
return std::wstring();
}
unsigned long long ContentLength() {
wchar_t buf[64] = {0};
DWORD size = sizeof(buf);
if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_CONTENT_LENGTH,
WINHTTP_HEADER_NAME_BY_INDEX, buf, &size,
WINHTTP_NO_HEADER_INDEX)) {
return _wcstoui64(buf, nullptr, 10);
}
return 0;
}
bool ReadAll(std::string& out) {
DWORD available = 0;
std::vector<char> chunk(64 * 1024);
for (;;) {
if (!WinHttpQueryDataAvailable(hRequest_, &available)) return false;
if (available == 0) break;
if (available > chunk.size()) chunk.resize(available);
DWORD read = 0;
if (!WinHttpReadData(hRequest_, chunk.data(), available, &read)) return false;
if (read == 0) break;
out.append(chunk.data(), read);
}
return true;
}
bool ReadToFile(HANDLE hFile, Http::ProgressFunc progress, unsigned long long total,
unsigned long long& written) {
DWORD available = 0;
std::vector<char> chunk(64 * 1024);
for (;;) {
if (!WinHttpQueryDataAvailable(hRequest_, &available)) return false;
if (available == 0) break;
if (available > chunk.size()) chunk.resize(available);
DWORD read = 0;
if (!WinHttpReadData(hRequest_, chunk.data(), available, &read)) return false;
if (read == 0) break;
DWORD done = 0;
while (done < read) {
DWORD step = 0;
if (!WriteFile(hFile, chunk.data() + done, read - done, &step, nullptr)) return false;
done += step;
}
written += read;
if (progress && !progress(written, total)) return false;
}
return true;
}
private:
UrlParts parts_;
HINTERNET hConnect_ = nullptr;
HINTERNET hRequest_ = nullptr;
bool opened_ = false;
};
}
static const int kMaxRedirect = 6;
bool Http::Get(const std::wstring& url, HttpResult& out, std::wstring& err) {
std::wstring current = url;
for (int i = 0; i < kMaxRedirect; ++i) {
Session session;
if (!session.valid()) { err = L"无法初始化网络"; return false; }
Request request(session.get(), current, false);
if (!request.opened()) { err = L"无法创建请求: " + current; return false; }
if (!request.Send()) { err = L"请求失败: " + current; return false; }
long status = request.Status();
if (status >= 300 && status < 400) {
std::wstring loc = request.Location();
std::wstring next = ResolveUrl(current, loc);
if (next.empty()) { err = L"重定向地址无效"; return false; }
current = next;
continue;
}
out.status = status;
if (!request.ReadAll(out.body)) { err = L"读取响应失败"; return false; }
return true;
}
err = L"重定向次数过多";
return false;
}
bool Http::Download(const std::wstring& url, const std::wstring& savePath,
ProgressFunc progress, std::wstring& err) {
std::wstring current = url;
for (int i = 0; i < kMaxRedirect; ++i) {
Session session;
if (!session.valid()) { err = L"无法初始化网络"; return false; }
Request request(session.get(), current, true);
if (!request.opened()) { err = L"无法创建请求: " + current; return false; }
if (!request.Send()) { err = L"请求失败: " + current; return false; }
long status = request.Status();
if (status >= 300 && status < 400) {
std::wstring loc = request.Location();
std::wstring next = ResolveUrl(current, loc);
if (next.empty()) { err = L"重定向地址无效"; return false; }
current = next;
continue;
}
if (status != 200) {
err = L"下载失败,HTTP " + std::to_wstring(status);
return false;
}
HANDLE hFile = CreateFileW(savePath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) { err = L"无法创建临时文件"; return false; }
unsigned long long written = 0;
bool ok = request.ReadToFile(hFile, progress, request.ContentLength(), written);
FlushFileBuffers(hFile);
CloseHandle(hFile);
if (!ok) {
DeleteFileW(savePath.c_str());
err = L"下载中断";
return false;
}
return true;
}
err = L"重定向次数过多";
return false;
}
}