HTTP.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*
  2. * HTTP.cpp
  3. * --------
  4. * Purpose: Simple HTTP client interface.
  5. * Notes : (currently none)
  6. * Authors: OpenMPT Devs
  7. * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
  8. */
  9. #include "stdafx.h"
  10. #include "HTTP.h"
  11. #include "mpt/system_error/system_error.hpp"
  12. #include <WinInet.h>
  13. #include "mpt/io/io.hpp"
  14. #include "mpt/io/io_stdstream.hpp"
  15. OPENMPT_NAMESPACE_BEGIN
  16. URI ParseURI(mpt::ustring str)
  17. {
  18. URI uri;
  19. std::size_t scheme_delim_pos = str.find(':');
  20. if(scheme_delim_pos == mpt::ustring::npos)
  21. {
  22. throw bad_uri("no scheme delimiter");
  23. }
  24. if(scheme_delim_pos == 0)
  25. {
  26. throw bad_uri("no scheme");
  27. }
  28. uri.scheme = str.substr(0, scheme_delim_pos);
  29. str = str.substr(scheme_delim_pos + 1);
  30. if(str.substr(0, 2) == U_("//"))
  31. {
  32. str = str.substr(2);
  33. std::size_t authority_delim_pos = str.find_first_of(U_("/?#"));
  34. mpt::ustring authority = str.substr(0, authority_delim_pos);
  35. std::size_t userinfo_delim_pos = authority.find(U_("@"));
  36. if(userinfo_delim_pos != mpt::ustring::npos)
  37. {
  38. mpt::ustring userinfo = authority.substr(0, userinfo_delim_pos);
  39. authority = authority.substr(userinfo_delim_pos + 1);
  40. std::size_t username_delim_pos = userinfo.find(U_(":"));
  41. uri.username = userinfo.substr(0, username_delim_pos);
  42. if(username_delim_pos != mpt::ustring::npos)
  43. {
  44. uri.password = userinfo.substr(username_delim_pos + 1);
  45. }
  46. }
  47. std::size_t beg_bracket_pos = authority.find(U_("["));
  48. std::size_t end_bracket_pos = authority.find(U_("]"));
  49. std::size_t port_delim_pos = authority.find_last_of(U_(":"));
  50. if(beg_bracket_pos != mpt::ustring::npos && end_bracket_pos != mpt::ustring::npos)
  51. {
  52. if(port_delim_pos != mpt::ustring::npos && port_delim_pos > end_bracket_pos)
  53. {
  54. uri.host = authority.substr(0, port_delim_pos);
  55. uri.port = authority.substr(port_delim_pos + 1);
  56. } else
  57. {
  58. uri.host = authority;
  59. }
  60. } else
  61. {
  62. uri.host = authority.substr(0, port_delim_pos);
  63. if(port_delim_pos != mpt::ustring::npos)
  64. {
  65. uri.port = authority.substr(port_delim_pos + 1);
  66. }
  67. }
  68. if(authority_delim_pos != mpt::ustring::npos)
  69. {
  70. str = str.substr(authority_delim_pos);
  71. } else
  72. {
  73. str = U_("");
  74. }
  75. }
  76. std::size_t path_delim_pos = str.find_first_of(U_("?#"));
  77. uri.path = str.substr(0, path_delim_pos);
  78. if(path_delim_pos != mpt::ustring::npos)
  79. {
  80. str = str.substr(path_delim_pos);
  81. std::size_t query_delim_pos = str.find(U_("#"));
  82. if(query_delim_pos != mpt::ustring::npos)
  83. {
  84. if(query_delim_pos > 0)
  85. {
  86. uri.query = str.substr(1, query_delim_pos - 1);
  87. uri.fragment = str.substr(query_delim_pos + 1);
  88. } else
  89. {
  90. uri.fragment = str.substr(query_delim_pos + 1);
  91. }
  92. } else
  93. {
  94. uri.query = str.substr(1);
  95. }
  96. }
  97. return uri;
  98. }
  99. namespace HTTP
  100. {
  101. exception::exception(const mpt::ustring &m)
  102. : std::runtime_error(std::string("HTTP error: ") + mpt::ToCharset(mpt::CharsetException, m))
  103. {
  104. message = m;
  105. }
  106. mpt::ustring exception::GetMessage() const
  107. {
  108. return message;
  109. }
  110. class LastErrorException
  111. : public exception
  112. {
  113. public:
  114. LastErrorException()
  115. : exception(mpt::windows::GetErrorMessage(GetLastError(), GetModuleHandle(TEXT("wininet.dll"))))
  116. {
  117. }
  118. };
  119. struct NativeHandle
  120. {
  121. HINTERNET native_handle;
  122. NativeHandle(HINTERNET h)
  123. : native_handle(h)
  124. {
  125. }
  126. operator HINTERNET() const
  127. {
  128. return native_handle;
  129. }
  130. };
  131. Handle::Handle()
  132. : handle(std::make_unique<NativeHandle>(HINTERNET(NULL)))
  133. {
  134. }
  135. Handle::operator bool() const
  136. {
  137. return handle->native_handle != HINTERNET(NULL);
  138. }
  139. bool Handle::operator!() const
  140. {
  141. return handle->native_handle == HINTERNET(NULL);
  142. }
  143. Handle::Handle(NativeHandle h)
  144. : handle(std::make_unique<NativeHandle>(HINTERNET(NULL)))
  145. {
  146. handle->native_handle = h.native_handle;
  147. }
  148. Handle & Handle::operator=(NativeHandle h)
  149. {
  150. if(handle->native_handle)
  151. {
  152. InternetCloseHandle(handle->native_handle);
  153. handle->native_handle = HINTERNET(NULL);
  154. }
  155. handle->native_handle = h.native_handle;
  156. return *this;
  157. }
  158. Handle::operator NativeHandle ()
  159. {
  160. return *handle;
  161. }
  162. Handle::~Handle()
  163. {
  164. if(handle->native_handle)
  165. {
  166. InternetCloseHandle(handle->native_handle);
  167. handle->native_handle = HINTERNET(NULL);
  168. }
  169. }
  170. InternetSession::InternetSession(mpt::ustring userAgent)
  171. {
  172. internet = NativeHandle(InternetOpen(mpt::ToWin(userAgent).c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0));
  173. if(!internet)
  174. {
  175. throw HTTP::LastErrorException();
  176. }
  177. }
  178. InternetSession::operator NativeHandle ()
  179. {
  180. return internet;
  181. }
  182. static mpt::winstring Verb(Method method)
  183. {
  184. mpt::winstring result;
  185. switch(method)
  186. {
  187. case Method::Get:
  188. result = _T("GET");
  189. break;
  190. case Method::Head:
  191. result = _T("HEAD");
  192. break;
  193. case Method::Post:
  194. result = _T("POST");
  195. break;
  196. case Method::Put:
  197. result = _T("PUT");
  198. break;
  199. case Method::Delete:
  200. result = _T("DELETE");
  201. break;
  202. case Method::Trace:
  203. result = _T("TRACE");
  204. break;
  205. case Method::Options:
  206. result = _T("OPTIONS");
  207. break;
  208. case Method::Connect:
  209. result = _T("CONNECT");
  210. break;
  211. case Method::Patch:
  212. result = _T("PATCH");
  213. break;
  214. }
  215. return result;
  216. }
  217. static bool IsCachable(Method method)
  218. {
  219. return method == Method::Get || method == Method::Head;
  220. }
  221. namespace
  222. {
  223. class AcceptMimeTypesWrapper
  224. {
  225. private:
  226. std::vector<mpt::winstring> strings;
  227. std::vector<LPCTSTR> array;
  228. public:
  229. AcceptMimeTypesWrapper(AcceptMimeTypes acceptMimeTypes)
  230. {
  231. for(const auto &mimeType : acceptMimeTypes)
  232. {
  233. strings.push_back(mpt::ToWin(mpt::Charset::ASCII, mimeType));
  234. }
  235. array.resize(strings.size() + 1);
  236. for(std::size_t i = 0; i < strings.size(); ++i)
  237. {
  238. array[i] = strings[i].c_str();
  239. }
  240. array[strings.size()] = NULL;
  241. }
  242. operator LPCTSTR*()
  243. {
  244. return strings.empty() ? NULL : array.data();
  245. }
  246. };
  247. }
  248. void Request::progress(Progress progress, uint64 transferred, std::optional<uint64> expectedSize) const
  249. {
  250. if(progressCallback)
  251. {
  252. progressCallback(progress, transferred, expectedSize);
  253. }
  254. }
  255. Result Request::operator()(InternetSession &internet) const
  256. {
  257. progress(Progress::Start, 0, std::nullopt);
  258. Port actualPort = port;
  259. if(actualPort == Port::Default)
  260. {
  261. actualPort = (protocol != Protocol::HTTP) ? Port::HTTPS : Port::HTTP;
  262. }
  263. Handle connection = NativeHandle(InternetConnect(
  264. NativeHandle(internet),
  265. mpt::ToWin(host).c_str(),
  266. static_cast<uint16>(actualPort),
  267. !username.empty() ? mpt::ToWin(username).c_str() : NULL,
  268. !password.empty() ? mpt::ToWin(password).c_str() : NULL,
  269. INTERNET_SERVICE_HTTP,
  270. 0,
  271. 0));
  272. if(!connection)
  273. {
  274. throw HTTP::LastErrorException();
  275. }
  276. progress(Progress::ConnectionEstablished, 0, std::nullopt);
  277. mpt::ustring queryPath = path;
  278. if(!query.empty())
  279. {
  280. std::vector<mpt::ustring> arguments;
  281. for(const auto &[key, value] : query)
  282. {
  283. if(!value.empty())
  284. {
  285. arguments.push_back(MPT_UFORMAT("{}={}")(key, value));
  286. } else
  287. {
  288. arguments.push_back(MPT_UFORMAT("{}")(key));
  289. }
  290. }
  291. queryPath += U_("?") + mpt::String::Combine(arguments, U_("&"));
  292. }
  293. Handle request = NativeHandle(HttpOpenRequest(
  294. NativeHandle(connection),
  295. Verb(method).c_str(),
  296. mpt::ToWin(path).c_str(),
  297. NULL,
  298. !referrer.empty() ? mpt::ToWin(referrer).c_str() : NULL,
  299. AcceptMimeTypesWrapper(acceptMimeTypes),
  300. 0
  301. | ((protocol != Protocol::HTTP) ? INTERNET_FLAG_SECURE : 0)
  302. | (IsCachable(method) ? 0 : INTERNET_FLAG_NO_CACHE_WRITE)
  303. | ((flags & NoCache) ? (INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE) : 0)
  304. | ((flags & AutoRedirect) ? 0 : INTERNET_FLAG_NO_AUTO_REDIRECT)
  305. ,
  306. NULL));
  307. if(!request)
  308. {
  309. throw HTTP::LastErrorException();
  310. }
  311. progress(Progress::RequestOpened, 0, std::nullopt);
  312. {
  313. std::string headersString;
  314. if(!dataMimeType.empty())
  315. {
  316. headersString += MPT_AFORMAT("Content-type: {}\r\n")(dataMimeType);
  317. }
  318. if(!headers.empty())
  319. {
  320. for(const auto &[key, value] : headers)
  321. {
  322. headersString += MPT_AFORMAT("{}: {}\r\n")(key, value);
  323. }
  324. }
  325. if(HttpSendRequest(
  326. NativeHandle(request),
  327. !headersString.empty() ? mpt::ToWin(mpt::Charset::ASCII, headersString).c_str() : NULL,
  328. !headersString.empty() ? mpt::saturate_cast<DWORD>(mpt::ToWin(mpt::Charset::ASCII, headersString).length()) : 0,
  329. !data.empty() ? (LPVOID)data.data() : NULL,
  330. !data.empty() ? mpt::saturate_cast<DWORD>(data.size()) : 0)
  331. == FALSE)
  332. {
  333. throw HTTP::LastErrorException();
  334. }
  335. }
  336. progress(Progress::RequestSent, 0, std::nullopt);
  337. Result result;
  338. {
  339. DWORD statusCode = 0;
  340. DWORD length = sizeof(statusCode);
  341. if(HttpQueryInfo(NativeHandle(request), HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &length, NULL) == FALSE)
  342. {
  343. throw HTTP::LastErrorException();
  344. }
  345. result.Status = statusCode;
  346. }
  347. progress(Progress::ResponseReceived, 0, std::nullopt);
  348. DWORD contentLength = static_cast<DWORD>(-1);
  349. {
  350. DWORD length = sizeof(contentLength);
  351. if(HttpQueryInfo(NativeHandle(request), HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentLength, &length, NULL) == FALSE)
  352. {
  353. contentLength = static_cast<DWORD>(-1);
  354. }
  355. }
  356. uint64 transferred = 0;
  357. if(contentLength != static_cast<DWORD>(-1))
  358. {
  359. result.ContentLength = contentLength;
  360. }
  361. std::optional<uint64> expectedSize = result.ContentLength;
  362. progress(Progress::TransferBegin, transferred, expectedSize);
  363. {
  364. std::vector<std::byte> resultBuffer;
  365. DWORD bytesRead = 0;
  366. do
  367. {
  368. std::array<std::byte, mpt::IO::BUFFERSIZE_TINY> downloadBuffer;
  369. DWORD availableSize = 0;
  370. if(InternetQueryDataAvailable(NativeHandle(request), &availableSize, 0, NULL) == FALSE)
  371. {
  372. throw HTTP::LastErrorException();
  373. }
  374. availableSize = std::clamp(availableSize, DWORD(0), mpt::saturate_cast<DWORD>(mpt::IO::BUFFERSIZE_TINY));
  375. if(InternetReadFile(NativeHandle(request), downloadBuffer.data(), availableSize, &bytesRead) == FALSE)
  376. {
  377. throw HTTP::LastErrorException();
  378. }
  379. if(outputStream)
  380. {
  381. if(!mpt::IO::WriteRaw(*outputStream, mpt::as_span(downloadBuffer).first(bytesRead)))
  382. {
  383. throw HTTP::exception(U_("Writing output file failed."));
  384. }
  385. } else
  386. {
  387. mpt::append(resultBuffer, downloadBuffer.data(), downloadBuffer.data() + bytesRead);
  388. }
  389. transferred += bytesRead;
  390. progress(Progress::TransferRunning, transferred, expectedSize);
  391. } while(bytesRead != 0);
  392. result.Data = std::move(resultBuffer);
  393. }
  394. progress(Progress::TransferDone, transferred, expectedSize);
  395. return result;
  396. }
  397. Request &Request::SetURI(const URI &uri)
  398. {
  399. if(uri.scheme == U_(""))
  400. {
  401. throw bad_uri("no scheme");
  402. } else if(uri.scheme == U_("http"))
  403. {
  404. protocol = HTTP::Protocol::HTTP;
  405. } else if(uri.scheme == U_("https"))
  406. {
  407. protocol = HTTP::Protocol::HTTPS;
  408. } else
  409. {
  410. throw bad_uri("wrong scheme");
  411. }
  412. host = uri.host;
  413. if(!uri.port.empty())
  414. {
  415. port = HTTP::Port(ConvertStrTo<uint16>(uri.port));
  416. } else
  417. {
  418. port = HTTP::Port::Default;
  419. }
  420. username = uri.username;
  421. password = uri.password;
  422. if(uri.path.empty())
  423. {
  424. path = U_("/");
  425. } else
  426. {
  427. path = uri.path;
  428. }
  429. query.clear();
  430. auto keyvals = mpt::String::Split<mpt::ustring>(uri.query, U_("&"));
  431. for(const auto &keyval : keyvals)
  432. {
  433. std::size_t delim_pos = keyval.find(U_("="));
  434. mpt::ustring key = keyval.substr(0, delim_pos);
  435. mpt::ustring val;
  436. if(delim_pos != mpt::ustring::npos)
  437. {
  438. val = keyval.substr(delim_pos + 1);
  439. }
  440. query.push_back(std::make_pair(key, val));
  441. }
  442. // ignore fragment
  443. return *this;
  444. }
  445. #if defined(MPT_BUILD_RETRO)
  446. Request &Request::InsecureTLSDowngradeWindowsXP()
  447. {
  448. if(mpt::OS::Windows::IsOriginal() && mpt::OS::Windows::Version::Current().IsBefore(mpt::OS::Windows::Version::WinVista))
  449. {
  450. // TLS 1.0 is not enabled by default until IE7. Since WinInet won't let us override this setting, we cannot assume that HTTPS
  451. // is going to work on older systems. Besides... Windows XP is already enough of a security risk by itself. :P
  452. if(protocol == Protocol::HTTPS)
  453. {
  454. protocol = Protocol::HTTP;
  455. }
  456. if(port == Port::HTTPS)
  457. {
  458. port = Port::HTTP;
  459. }
  460. }
  461. return *this;
  462. }
  463. #endif // MPT_BUILD_RETRO
  464. Result SimpleGet(InternetSession &internet, Protocol protocol, const mpt::ustring &host, const mpt::ustring &path)
  465. {
  466. HTTP::Request request;
  467. request.protocol = protocol;
  468. request.host = host;
  469. request.method = HTTP::Method::Get;
  470. request.path = path;
  471. return internet(request);
  472. }
  473. } // namespace HTTP
  474. OPENMPT_NAMESPACE_END