http_execute.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (c) 2017-2023 zhllxt
  3. *
  4. * author : zhllxt
  5. * email : 37792738@qq.com
  6. *
  7. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. */
  10. #ifndef __ASIO2_HTTP_EXECUTE_HPP__
  11. #define __ASIO2_HTTP_EXECUTE_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <asio2/base/detail/push_options.hpp>
  16. #include <asio2/base/detail/function_traits.hpp>
  17. #include <asio2/util/string.hpp>
  18. #include <asio2/http/detail/http_util.hpp>
  19. #include <asio2/http/detail/http_make.hpp>
  20. #include <asio2/http/detail/http_traits.hpp>
  21. #include <asio2/component/socks/socks5_client_cp.hpp>
  22. namespace asio2::detail
  23. {
  24. template<class derived_t, class args_t, bool Enable = is_http_execute_download_enabled<args_t>::value()>
  25. struct http_execute_impl_bridge;
  26. template<class derived_t, class args_t>
  27. struct http_execute_impl_bridge<derived_t, args_t, false>
  28. {
  29. };
  30. template<class derived_t, class args_t>
  31. struct http_execute_impl_bridge<derived_t, args_t, true>
  32. {
  33. protected:
  34. template<typename String, typename StrOrInt, class Proxy, class Body, class Fields, class Buffer>
  35. static void _execute_with_socks5(
  36. asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
  37. http::parser<false, Body, typename Fields::allocator_type>& parser,
  38. Buffer& buffer,
  39. String&& host, StrOrInt&& port,
  40. http::request<Body, Fields>& req, Proxy&& proxy)
  41. {
  42. auto sk5 = detail::to_shared_ptr(std::forward<Proxy>(proxy));
  43. std::string_view h{ sk5->host() };
  44. std::string_view p{ sk5->port() };
  45. if (static_cast<int>(sk5->command()) == 0)
  46. {
  47. sk5->command(socks5::command::connect);
  48. }
  49. // Look up the domain name
  50. resolver.async_resolve(h, p, [&, s5 = std::move(sk5)]
  51. (const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
  52. {
  53. if (ec1) { set_last_error(ec1); return; }
  54. // Make the connection on the IP address we get from a lookup
  55. asio::async_connect(socket, endpoints,
  56. [&, s5 = std::move(s5)](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
  57. {
  58. if (ec2) { set_last_error(ec2); return; }
  59. socks5_async_handshake
  60. (
  61. detail::to_string(std::forward<String >(host)),
  62. detail::to_string(std::forward<StrOrInt>(port)),
  63. socket,
  64. std::move(s5),
  65. [&](error_code ecs5, std::string, std::string) mutable
  66. {
  67. if (ecs5) { set_last_error(ecs5); return; }
  68. http::async_write(socket, req, [&](const error_code & ec3, std::size_t) mutable
  69. {
  70. if (ec3) { set_last_error(ec3); return; }
  71. // Then start asynchronous reading
  72. http::async_read(socket, buffer, parser,
  73. [&](const error_code& ec4, std::size_t) mutable
  74. {
  75. // Reading completed, assign the read the result to last error
  76. // If the code does not execute into here, the last error
  77. // is the default value timed_out.
  78. set_last_error(ec4);
  79. });
  80. });
  81. }
  82. );
  83. });
  84. });
  85. }
  86. template<typename String, typename StrOrInt, class Body, class Fields, class Buffer>
  87. static void _execute_trivially(
  88. asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
  89. http::parser<false, Body, typename Fields::allocator_type>& parser,
  90. Buffer& buffer,
  91. String&& host, StrOrInt&& port,
  92. http::request<Body, Fields>& req)
  93. {
  94. detail::ignore_unused(ioc);
  95. // Look up the domain name
  96. resolver.async_resolve(std::forward<String>(host), detail::to_string(std::forward<StrOrInt>(port)),
  97. [&](const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
  98. {
  99. if (ec1) { set_last_error(ec1); return; }
  100. // Make the connection on the IP address we get from a lookup
  101. asio::async_connect(socket, endpoints,
  102. [&](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
  103. {
  104. if (ec2) { set_last_error(ec2); return; }
  105. http::async_write(socket, req, [&](const error_code & ec3, std::size_t) mutable
  106. {
  107. if (ec3) { set_last_error(ec3); return; }
  108. // Then start asynchronous reading
  109. http::async_read(socket, buffer, parser,
  110. [&](const error_code& ec4, std::size_t) mutable
  111. {
  112. // Reading completed, assign the read the result to last error
  113. // If the code does not execute into here, the last error
  114. // is the default value timed_out.
  115. set_last_error(ec4);
  116. });
  117. });
  118. });
  119. });
  120. }
  121. template<typename String, typename StrOrInt, class Proxy, class Body, class Fields, class Buffer>
  122. static void _execute_impl(
  123. asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
  124. http::parser<false, Body, typename Fields::allocator_type>& parser,
  125. Buffer& buffer,
  126. String&& host, StrOrInt&& port,
  127. http::request<Body, Fields>& req, Proxy&& proxy)
  128. {
  129. // if has socks5 proxy
  130. if constexpr (std::is_base_of_v<asio2::socks5::option_base,
  131. typename detail::element_type_adapter<detail::remove_cvref_t<Proxy>>::type>)
  132. {
  133. derived_t::_execute_with_socks5(ioc, resolver, socket, parser, buffer
  134. , std::forward<String>(host), std::forward<StrOrInt>(port)
  135. , req
  136. , std::forward<Proxy>(proxy)
  137. );
  138. }
  139. else
  140. {
  141. detail::ignore_unused(proxy);
  142. derived_t::_execute_trivially(ioc, resolver, socket, parser, buffer
  143. , std::forward<String>(host), std::forward<StrOrInt>(port)
  144. , req
  145. );
  146. }
  147. }
  148. public:
  149. template<typename String, typename StrOrInt, class Rep, class Period, class Proxy,
  150. class Body = http::string_body, class Fields = http::fields, class Buffer = beast::flat_buffer>
  151. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  152. && detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  153. static inline execute(String&& host, StrOrInt&& port,
  154. http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
  155. {
  156. http::parser<false, Body, typename Fields::allocator_type> parser;
  157. // First assign default value timed_out to last error
  158. set_last_error(asio::error::timed_out);
  159. // set default result to unknown
  160. parser.get().result(http::status::unknown);
  161. parser.eager(true);
  162. // The io_context is required for all I/O
  163. asio::io_context ioc;
  164. // These objects perform our I/O
  165. asio::ip::tcp::resolver resolver{ ioc };
  166. asio::ip::tcp::socket socket{ ioc };
  167. // This buffer is used for reading and must be persisted
  168. Buffer buffer;
  169. // Some sites must set the http::field::host
  170. if (req.find(http::field::host) == req.end())
  171. {
  172. std::string strhost = asio2::to_string(host);
  173. std::string strport = asio2::to_string(port);
  174. if (strport != "80")
  175. {
  176. strhost += ":";
  177. strhost += strport;
  178. }
  179. req.set(http::field::host, strhost);
  180. }
  181. // Some sites must set the http::field::user_agent
  182. if (req.find(http::field::user_agent) == req.end())
  183. {
  184. req.set(http::field::user_agent,
  185. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36");
  186. }
  187. // do work
  188. derived_t::_execute_impl(ioc, resolver, socket, parser, buffer
  189. , std::forward<String>(host), std::forward<StrOrInt>(port)
  190. , req, std::forward<Proxy>(proxy)
  191. );
  192. // timedout run
  193. ioc.run_for(timeout);
  194. error_code ec_ignore{};
  195. // Gracefully close the socket
  196. socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
  197. socket.cancel(ec_ignore);
  198. socket.close(ec_ignore);
  199. return parser.release();
  200. }
  201. // ----------------------------------------------------------------------------------------
  202. template<typename String, typename StrOrInt, class Rep, class Period,
  203. class Body = http::string_body, class Fields = http::fields>
  204. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  205. , http::response<Body, Fields>>
  206. static inline execute(String&& host, StrOrInt&& port,
  207. http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout)
  208. {
  209. return derived_t::execute(
  210. std::forward<String>(host), std::forward<StrOrInt>(port), req, timeout, std::in_place);
  211. }
  212. template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
  213. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  214. , http::response<Body, Fields>>
  215. static inline execute(String&& host, StrOrInt&& port, http::request<Body, Fields>& req)
  216. {
  217. return derived_t::execute(
  218. std::forward<String>(host), std::forward<StrOrInt>(port),
  219. req, std::chrono::milliseconds(http_execute_timeout));
  220. }
  221. // ----------------------------------------------------------------------------------------
  222. template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
  223. static inline http::response<Body, Fields> execute(
  224. http::web_request& req, std::chrono::duration<Rep, Period> timeout)
  225. {
  226. return derived_t::execute(req.url().host(), req.url().port(), req.base(), timeout, std::in_place);
  227. }
  228. template<class Body = http::string_body, class Fields = http::fields>
  229. static inline http::response<Body, Fields> execute(http::web_request& req)
  230. {
  231. return derived_t::execute(req, std::chrono::milliseconds(http_execute_timeout));
  232. }
  233. // ----------------------------------------------------------------------------------------
  234. /**
  235. * @brief blocking execute the http request until it is returned on success or failure
  236. */
  237. template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
  238. static inline http::response<Body, Fields> execute(std::string_view url,
  239. std::chrono::duration<Rep, Period> timeout)
  240. {
  241. http::web_request req = http::make_request(url);
  242. if (get_last_error())
  243. {
  244. return http::response<Body, Fields>{ http::status::unknown, 11};
  245. }
  246. return derived_t::execute(
  247. req.host(), req.port(), req.base(), timeout, std::in_place);
  248. }
  249. /**
  250. * @brief blocking execute the http request until it is returned on success or failure
  251. */
  252. template<class Body = http::string_body, class Fields = http::fields>
  253. static inline http::response<Body, Fields> execute(std::string_view url)
  254. {
  255. return derived_t::execute(url, std::chrono::milliseconds(http_execute_timeout));
  256. }
  257. // ----------------------------------------------------------------------------------------
  258. /**
  259. * @brief blocking execute the http request until it is returned on success or failure
  260. */
  261. template<typename String, typename StrOrInt, class Rep, class Period,
  262. class Body = http::string_body, class Fields = http::fields>
  263. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  264. , http::response<Body, Fields>>
  265. static inline execute(String&& host, StrOrInt&& port,
  266. std::string_view target, std::chrono::duration<Rep, Period> timeout)
  267. {
  268. http::web_request req = http::make_request(host, port, target);
  269. if (get_last_error())
  270. {
  271. return http::response<Body, Fields>{ http::status::unknown, 11};
  272. }
  273. return derived_t::execute(
  274. std::forward<String>(host), std::forward<StrOrInt>(port),
  275. req.base(), timeout, std::in_place);
  276. }
  277. /**
  278. * @brief blocking execute the http request until it is returned on success or failure
  279. */
  280. template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
  281. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  282. , http::response<Body, Fields>>
  283. static inline execute(String&& host, StrOrInt&& port, std::string_view target)
  284. {
  285. return derived_t::execute(
  286. std::forward<String>(host), std::forward<StrOrInt>(port),
  287. target, std::chrono::milliseconds(http_execute_timeout));
  288. }
  289. // ----------------------------------------------------------------------------------------
  290. template<typename String, typename StrOrInt, class Proxy,
  291. class Body = http::string_body, class Fields = http::fields>
  292. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  293. && detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  294. static inline execute(String&& host, StrOrInt&& port, http::request<Body, Fields>& req, Proxy&& proxy)
  295. {
  296. return derived_t::execute(
  297. std::forward<String>(host), std::forward<StrOrInt>(port),
  298. req, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
  299. }
  300. // ----------------------------------------------------------------------------------------
  301. template<class Rep, class Period, class Proxy, class Body = http::string_body, class Fields = http::fields>
  302. typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  303. static inline execute(http::web_request& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
  304. {
  305. return derived_t::execute(req.url().host(), req.url().port(), req.base(), timeout,
  306. std::forward<Proxy>(proxy));
  307. }
  308. template<class Proxy, class Body = http::string_body, class Fields = http::fields>
  309. typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  310. static inline execute(http::web_request& req, Proxy&& proxy)
  311. {
  312. return derived_t::execute(req, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
  313. }
  314. // ----------------------------------------------------------------------------------------
  315. /**
  316. * @brief blocking execute the http request until it is returned on success or failure
  317. */
  318. template<class Rep, class Period, class Proxy, class Body = http::string_body, class Fields = http::fields>
  319. typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  320. static inline execute(std::string_view url, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
  321. {
  322. http::web_request req = http::make_request(url);
  323. if (get_last_error())
  324. {
  325. return http::response<Body, Fields>{ http::status::unknown, 11};
  326. }
  327. return derived_t::execute(req.host(), req.port(), req.base(), timeout, std::forward<Proxy>(proxy));
  328. }
  329. /**
  330. * @brief blocking execute the http request until it is returned on success or failure
  331. */
  332. template<class Proxy, class Body = http::string_body, class Fields = http::fields>
  333. typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  334. static inline execute(std::string_view url, Proxy&& proxy)
  335. {
  336. return derived_t::execute(url, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
  337. }
  338. // ----------------------------------------------------------------------------------------
  339. /**
  340. * @brief blocking execute the http request until it is returned on success or failure
  341. */
  342. template<typename String, typename StrOrInt, class Rep, class Period, class Proxy,
  343. class Body = http::string_body, class Fields = http::fields>
  344. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  345. && detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  346. static inline execute(String&& host, StrOrInt&& port,
  347. std::string_view target, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
  348. {
  349. http::web_request req = http::make_request(host, port, target);
  350. if (get_last_error())
  351. {
  352. return http::response<Body, Fields>{ http::status::unknown, 11};
  353. }
  354. return derived_t::execute(
  355. std::forward<String>(host), std::forward<StrOrInt>(port),
  356. req.base(), timeout, std::forward<Proxy>(proxy));
  357. }
  358. /**
  359. * @brief blocking execute the http request until it is returned on success or failure
  360. */
  361. template<typename String, typename StrOrInt, class Proxy,
  362. class Body = http::string_body, class Fields = http::fields>
  363. typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
  364. && detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
  365. static inline execute(String&& host, StrOrInt&& port, std::string_view target, Proxy&& proxy)
  366. {
  367. return derived_t::execute(
  368. std::forward<String>(host), std::forward<StrOrInt>(port),
  369. target, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
  370. }
  371. };
  372. template<class derived_t, class args_t = void>
  373. struct http_execute_impl : public http_execute_impl_bridge<derived_t, args_t> {};
  374. }
  375. #include <asio2/base/detail/pop_options.hpp>
  376. #endif // !__ASIO2_HTTP_EXECUTE_HPP__