win_http.cpp 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
#include "stdafx.h"

#include "etradeclient/utility/win_http.h"

#include <memory>
#include <vector>
#include <sstream>
#include <cctype>
#include <regex>
#include <boost/algorithm/string.hpp>

#include "wincrypt.h"

#include "etradeclient/utility/string_converter.h"
#include "application_config.h"
#include "logging.h"

namespace
{
	typedef std::vector<std::pair<std::wstring, std::wstring>> CookieItems;
	std::wstring GetCookieItem(CookieItems::const_iterator first, CookieItems::const_iterator last, const std::wstring& item)
	{
		auto it = std::find_if(first, last,
			[&](const CookieItems::value_type& elem)
			{
				return boost::iequals(elem.first, item);
			});
		if (it != last)
			return it->second;
		else
			return L"";
	}
}

WinHttp::WinHttp() : m_is_https(false), m_session(nullptr), m_connect(nullptr)
{
	// Use WinHttpOpen to obtain a session handle, all the subsequent request are based on this session context.
	m_session = WinHttpOpen(L"WinHTTP Request", // This param can be any string, even empty string.
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME,
		WINHTTP_NO_PROXY_BYPASS, 0);

	if (!m_session)
	{
		std::string err_msg = "获取WinHTTP会话句柄失败!错误代码:" + std::to_string(GetLastError());
		throw std::exception(err_msg.c_str());
	}
}

WinHttp::~WinHttp()
{
	// Close all handles so that all resources are released.
	DisconnectHost();
	if (m_session)
	{
		WinHttpCloseHandle(m_session);
		m_session = nullptr;
	}
}

void WinHttp::ConnectHost(const std::string& host, uint16_t port, bool is_https)
{
	m_is_https = is_https;
	m_connect = WinHttpConnect(m_session, str_2_wstr(host).c_str(), port, 0);
	if (!m_connect)
	{
		std::string err_msg = "建立WinHttp连接失败!错误代码:" + std::to_string(GetLastError());
		throw std::exception(err_msg.c_str());
	}
}

void WinHttp::DisconnectHost()
{
	if (m_connect)
	{
		WinHttpCloseHandle(m_connect);
		m_connect = nullptr;
	}
}

WinHttp::Request WinHttp::OpenRequest(const Method& method, const std::string& res_path)
{
	std::wstring method_name;
	switch (method)
	{
	case Method::GET:
		method_name = L"GET";
		break;
	case Method::POST:
		method_name = L"POST";
		break;
	}
	// Create an HTTP request handle.
	HINTERNET handle = WinHttpOpenRequest(m_connect, method_name.c_str(), str_2_wstr(res_path).c_str(),
		NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, m_is_https ? WINHTTP_FLAG_SECURE : 0);
	if (!handle)
	{
		std::string err_msg = "创建WinHttp请求失败!错误代码:" + std::to_string(GetLastError());
		throw std::exception(err_msg.c_str());
	}
	return Request(handle, method);
}

void WinHttp::CloseRequest(Request& req)
{
	req.Close();
}

//--------------------------------------------------------------------------

WinHttp::Request::Request(Request&& rhs)
{
	m_request = std::move(rhs.m_request);
	rhs.m_request = NULL;
	m_method = rhs.m_method;
	m_post_data = std::move(rhs.m_post_data);
}

WinHttp::Request& WinHttp::Request::operator=(Request&& rhs)
{
	if (this != &rhs)
	{
		m_request = std::move(rhs.m_request);
		rhs.m_request = NULL;
		m_method = rhs.m_method;
		m_post_data = std::move(rhs.m_post_data);
	}
	return *this;
}

WinHttp::Request::Request(HINTERNET handle, const WinHttp::Method& method) : m_request(handle), m_method(method)
{}

WinHttp::Request::~Request()
{
	Close();
}

void WinHttp::Request::SetCookies(const Cookies& cookies)
{
	std::stringstream cookie_str;
	cookie_str << "Cookie: ";
	for (const auto& cookie : cookies)
	{
		cookie_str << cookie.name << "=" << cookie.value << "; ";
		cookie_str << "domain: " << cookie.domain << "; ";
		cookie_str << "httponly: " << cookie.httponly << "; ";
		cookie_str << "path: " << cookie.path << "; ";
		cookie_str << "secure: " << cookie.secure << "; ";
	}
	WinHttpAddRequestHeaders(m_request, str_2_wstr(cookie_str.str()).c_str(), -1, WINHTTP_ADDREQ_FLAG_ADD);
}

void WinHttp::Request::SetClientCertificate(const std::string& cert_store_name, const std::string& subject_name)
{
	HCERTSTORE cert_store = CertOpenSystemStore(0, str_2_wstr(cert_store_name).c_str());
	if (cert_store)
	{
		PCCERT_CONTEXT cert_context = CertFindCertificateInStore(cert_store,
			X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
			0,
			CERT_FIND_SUBJECT_STR,
			str_2_wstr(subject_name).c_str(), //Issuer string in the certificate.
			NULL);
		if (cert_context)
		{
			WinHttpSetOption(m_request,
				WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
				(LPVOID)cert_context,
				sizeof(CERT_CONTEXT));
			CertFreeCertificateContext(cert_context);
		}
		else
		{
			LOG_TRACE(L"证书未找到,正在重新安装。");
			auto& stuAppCfg = ApplicationConfig::Instance();
			HANDLE pFile;
			pFile = ::CreateFile(str_2_wstr(stuAppCfg.ClientCertFileName()).c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL, NULL); // 用这个函数比OpenFile好

			if (pFile != INVALID_HANDLE_VALUE)
			{
				DWORD dwFilesize = GetFileSize(pFile, NULL);
				char* cBuffer = new char[dwFilesize + 1]; // 最后一位为 '/0',C-Style 字符串的结束符
				DWORD dwReadsize;
				ReadFile(pFile, cBuffer, dwFilesize, &dwReadsize, NULL);
				cBuffer[dwFilesize] = 0;

				CRYPT_DATA_BLOB stuPFX;
				stuPFX.cbData = dwReadsize;
				stuPFX.pbData = (BYTE *)CryptMemAlloc(stuPFX.cbData);

				memcpy(stuPFX.pbData, cBuffer, dwReadsize);

				HCERTSTORE hCertStore = PFXImportCertStore(&stuPFX, str_2_wstr(stuAppCfg.ClientCertPassword()).c_str(), CRYPT_EXPORTABLE);

				PCCERT_CONTEXT stuPFXContext = CertFindCertificateInStore(hCertStore,
					X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
					0,
					CERT_FIND_SUBJECT_STR,
					str_2_wstr(subject_name).c_str(), //Issuer string in the certificate.
					NULL);

				if (CertAddCertificateContextToStore(cert_store, stuPFXContext, CERT_STORE_ADD_NEW, NULL))
				{
					LOG_TRACE(L"证书安装成功。");
				}
				else
				{
					LOG_TRACE(L"证书安装失败。");
				}

				// 善后工作
				delete[] cBuffer;
				CloseHandle(pFile); // 关闭句柄
				CryptMemFree(stuPFX.pbData);
				CertFreeCertificateContext(stuPFXContext);

				LOG_TRACE(L"重新查找证书。");
				PCCERT_CONTEXT cert_context = CertFindCertificateInStore(cert_store,
					X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
					0,
					CERT_FIND_SUBJECT_STR,
					str_2_wstr(subject_name).c_str(), //Issuer string in the certificate.
					NULL);
				if (cert_context)
				{
					WinHttpSetOption(m_request,
						WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
						(LPVOID)cert_context,
						sizeof(CERT_CONTEXT));
					CertFreeCertificateContext(cert_context);
					CertCloseStore(cert_store, 0);
				}
				else
				{
					std::string err_msg("打开认证存储区域失败!错误代码:" + std::to_string(GetLastError()));
					throw std::exception(err_msg.c_str());
				}

			}
			else
			{
				LOG_TRACE(L"证书文件未找到。");
				std::string err_msg("打开认证存储区域失败!错误代码:" + std::to_string(GetLastError()));
				throw std::exception(err_msg.c_str());
			}
		}
		CertCloseStore(cert_store, 0);
	}
	else
	{
		std::string err_msg("打开认证存储区域失败!错误代码:" + std::to_string(GetLastError()));
		throw std::exception(err_msg.c_str());
	}
}

void WinHttp::Request::SetPostData(const std::string& post_data)
{
	m_post_data = post_data;
}

void WinHttp::Request::Send()
{
	switch (m_method)
	{
	case Method::GET:
		Get();
		break;
	case Method::POST:
		Post();
		break;
	case Method::JSONPOST:
		JsonPost();
		break;
	default:
		return;
	}
	// Read the response data.
	if (TRUE != WinHttpReceiveResponse(m_request, NULL)) // Avoid warning C4800: 'BOOL' : forcing value to bool 'true' or 'false
	{
		std::string err_msg("接收WinHttp响应数据失败!错误代码:" + std::to_string(GetLastError()));
		throw std::exception(err_msg.c_str());
	}
}

std::string WinHttp::Request::ReadResponseHeader() const
{
	std::wstring header(L"");
	QuerySingleHeader(header, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_NO_HEADER_INDEX);
	return wstr_2_str(header);
}

std::string WinHttp::Request::ReadResponseBody() const
{
	DWORD data_size = 0;
	DWORD num_of_bytes_read = 0;
	std::string response_data("");
	do
	{
		data_size = 0;
		if (!WinHttpQueryDataAvailable(m_request, &data_size)) // Check for available data.
		{
			std::string err_msg("获取WinHttp响应数据失败!错误代码:" + std::to_string(GetLastError()));
			throw std::exception(err_msg.c_str());
		}
		if (data_size > 0)
		{
			std::unique_ptr<char[]> buffer(new char[data_size + 1]);
			if (nullptr == buffer)
			{
				std::string err_msg("读取WinHttp响应数据时内存分配失败!错误代码:" + std::to_string(GetLastError()));
				throw std::exception(err_msg.c_str());
			}
			else
			{
				// Read the data.
				ZeroMemory(buffer.get(), data_size + 1);
				if (!WinHttpReadData(m_request, buffer.get(), data_size, &num_of_bytes_read))
				{
					std::string err_msg("读取WinHttp响应数据失败!错误代码:" + std::to_string(GetLastError()));
					throw std::exception(err_msg.c_str());
				}
				response_data.append(buffer.get(), data_size);
			}
			buffer.reset(nullptr); // Release buffer memory.
		}
	} while (data_size > 0);
	return response_data;
}

uint32_t WinHttp::Request::GetResponseStatus() const
{
	std::wstring header;
	QuerySingleHeader(header, WINHTTP_QUERY_STATUS_CODE, WINHTTP_NO_HEADER_INDEX);
	return header.empty() ? 0 : stoi(header);
}

WinHttp::Cookies WinHttp::Request::GetCookies() const
{
	Cookies cookies;
	std::list<std::wstring> header_list;
	QueryMultiHeader(header_list, WINHTTP_QUERY_SET_COOKIE);

	if (!header_list.empty())
		ParseCookies(header_list, cookies);
	return cookies;
}

void WinHttp::Request::Get()
{
	if (!WinHttpSendRequest(m_request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
	{
		std::string err_msg("发送WinHttp Get请求失败!错误代码:" + std::to_string(GetLastError()));
		throw std::exception(err_msg.c_str());
	}
}

void WinHttp::Request::Post()
{
	// Send a request.
	if (!WinHttpSendRequest(m_request,
		L"Content-Type: application/x-www-form-urlencoded; charset=UTF-8", // headers.
		-1,
		const_cast<char*>(m_post_data.c_str()),
		m_post_data.size(),
		m_post_data.size(),
		0))
	{
		std::string err_msg("发送WinHttp Post请求失败!错误代码:" + std::to_string(GetLastError()));
		throw std::exception(err_msg.c_str());
	}
}

void WinHttp::Request::JsonPost()
{
	// Send a request.
	if (!WinHttpSendRequest(m_request,
		L"Content-Type: application/json; charset=UTF-8", // headers.
		-1,
		const_cast<char*>(m_post_data.c_str()),
		m_post_data.size(),
		m_post_data.size(),
		0))
	{
		std::string err_msg("发送WinHttp Post请求失败!错误代码:" + std::to_string(GetLastError()));
		throw std::exception(err_msg.c_str());
	}
}

void WinHttp::Request::QuerySingleHeader(std::wstring& header, uint32_t query_info_flag, DWORD* header_idx) const
{
	DWORD buff_len = 0;
	WinHttpQueryHeaders(m_request, query_info_flag, WINHTTP_HEADER_NAME_BY_INDEX, WINHTTP_NO_OUTPUT_BUFFER, &buff_len, header_idx);

	// Allocate memory for the buffer.
	if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && buff_len > 0)
	{
		std::unique_ptr<wchar_t[]> buffer(new wchar_t[buff_len / 2 + 1]);
		if (nullptr != buffer)
		{
			ZeroMemory(buffer.get(), buff_len / 2 + 1);
			// Now, use WinHttpQueryHeaders to retrieve the header.
			if (WinHttpQueryHeaders(m_request, query_info_flag, WINHTTP_HEADER_NAME_BY_INDEX, buffer.get(), &buff_len, header_idx))
				header.assign(buffer.get());
			else
			{
				std::string err_msg("读取WinHttp Header数据失败!错误代码:" + std::to_string(GetLastError()));
				throw std::exception(err_msg.c_str());
			}
		}
	}
}

void WinHttp::Request::QueryMultiHeader(std::list<std::wstring>& header_list, uint32_t query_info_flag) const
{
	DWORD header_idx = 0;
	while (true)
	{
		std::wstring header(L"");
		QuerySingleHeader(header, query_info_flag, &header_idx);
		if (header.empty())
			break; // No more header.
		else
			header_list.emplace_back(std::move(header));
	}
}

void WinHttp::Request::ParseCookies(const std::list<std::wstring>& header_list, Cookies& cookies) const
{
	const std::wregex reg_exp(L"(\\w+)=([^;]*)");
	for (const std::wstring& item : header_list)
	{
		CookieItems cookie_items;
		std::regex_iterator<std::wstring::const_iterator> r_cit(item.cbegin(), item.cend(), reg_exp);
		std::regex_iterator<std::wstring::const_iterator> r_cend;

		while (r_cit != r_cend)
		{
			// WARNING!!! Order is important here, because we assume the first item of a cookie is always the "name=value" pair.
			// That's why we use std::vector & emplace_back here instead of the "std::map".
			cookie_items.emplace_back((*r_cit)[1], (*r_cit)[2]/*value*/); 
			++r_cit;
		}

		if (!cookie_items.empty())
		{
			WinHttp::Cookie cookie;
			// WARNING!!! Order is important here, because we assume the first item of a cookie is always the "name=value" pair.
			auto cbegin = cookie_items.cbegin();
			cookie.name = wstr_2_str(cbegin->first);
			cookie.value = wstr_2_str(cbegin->second);
			++cbegin;

			cookie.domain = wstr_2_str(GetCookieItem(cbegin, cookie_items.cend(), L"domain"));
			cookie.path = wstr_2_str(GetCookieItem(cbegin, cookie_items.cend(), L"path"));
			cookie.secure = boost::iequals(GetCookieItem(cbegin, cookie_items.cend(), L"secure"), L"true");
			cookie.httponly = boost::iequals(GetCookieItem(cbegin, cookie_items.cend(), L"httponly"), L"true");
			cookies.emplace_back(std::move(cookie));
		}
	}
}

void WinHttp::Request::Close()
{
	if (m_request)
	{
		WinHttpCloseHandle(m_request);
		m_request = nullptr;
	}
}