handshake.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_WEBSOCKET_IMPL_HANDSHAKE_HPP
  10. #define BOOST_BEAST_WEBSOCKET_IMPL_HANDSHAKE_HPP
  11. #include <boost/beast/websocket/impl/stream_impl.hpp>
  12. #include <boost/beast/websocket/detail/type_traits.hpp>
  13. #include <boost/beast/http/empty_body.hpp>
  14. #include <boost/beast/http/message.hpp>
  15. #include <boost/beast/http/read.hpp>
  16. #include <boost/beast/http/write.hpp>
  17. #include <boost/beast/core/async_base.hpp>
  18. #include <boost/beast/core/flat_buffer.hpp>
  19. #include <boost/beast/core/stream_traits.hpp>
  20. #include <boost/asio/coroutine.hpp>
  21. #include <boost/assert.hpp>
  22. #include <boost/throw_exception.hpp>
  23. #include <memory>
  24. namespace boost {
  25. namespace beast {
  26. namespace websocket {
  27. //------------------------------------------------------------------------------
  28. // send the upgrade request and process the response
  29. //
  30. template<class NextLayer, bool deflateSupported>
  31. template<class Handler>
  32. class stream<NextLayer, deflateSupported>::handshake_op
  33. : public beast::stable_async_base<Handler,
  34. beast::executor_type<stream>>
  35. , public asio::coroutine
  36. {
  37. struct data
  38. {
  39. // VFALCO This really should be two separate
  40. // composed operations, to save on memory
  41. request_type req;
  42. http::response_parser<
  43. typename response_type::body_type> p;
  44. flat_buffer fb;
  45. bool overflow = false; // could be a member of the op
  46. explicit
  47. data(request_type&& req_)
  48. : req(std::move(req_))
  49. {
  50. }
  51. };
  52. boost::weak_ptr<impl_type> wp_;
  53. detail::sec_ws_key_type key_;
  54. response_type* res_p_;
  55. data& d_;
  56. public:
  57. template<class Handler_>
  58. handshake_op(
  59. Handler_&& h,
  60. boost::shared_ptr<impl_type> const& sp,
  61. request_type&& req,
  62. detail::sec_ws_key_type key,
  63. response_type* res_p)
  64. : stable_async_base<Handler,
  65. beast::executor_type<stream>>(
  66. std::forward<Handler_>(h),
  67. sp->stream().get_executor())
  68. , wp_(sp)
  69. , key_(key)
  70. , res_p_(res_p)
  71. , d_(beast::allocate_stable<data>(
  72. *this, std::move(req)))
  73. {
  74. sp->reset(); // VFALCO I don't like this
  75. if(res_p)
  76. res_p->result(http::status::internal_server_error);
  77. (*this)({}, 0, false);
  78. }
  79. void
  80. operator()(
  81. error_code ec = {},
  82. std::size_t bytes_used = 0,
  83. bool cont = true)
  84. {
  85. boost::ignore_unused(bytes_used);
  86. auto sp = wp_.lock();
  87. if(! sp)
  88. {
  89. BOOST_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  90. return this->complete(cont, ec);
  91. }
  92. auto& impl = *sp;
  93. BOOST_ASIO_CORO_REENTER(*this)
  94. {
  95. impl.change_status(status::handshake);
  96. impl.update_timer(this->get_executor());
  97. // write HTTP request
  98. impl.do_pmd_config(d_.req);
  99. BOOST_ASIO_CORO_YIELD
  100. {
  101. BOOST_ASIO_HANDLER_LOCATION((
  102. __FILE__, __LINE__,
  103. "websocket::async_handshake"));
  104. http::async_write(impl.stream(),
  105. d_.req, std::move(*this));
  106. }
  107. if(impl.check_stop_now(ec))
  108. goto upcall;
  109. // read HTTP response
  110. BOOST_ASIO_CORO_YIELD
  111. {
  112. BOOST_ASIO_HANDLER_LOCATION((
  113. __FILE__, __LINE__,
  114. "websocket::async_handshake"));
  115. http::async_read(impl.stream(),
  116. impl.rd_buf, d_.p,
  117. std::move(*this));
  118. }
  119. if(ec == http::error::buffer_overflow)
  120. {
  121. // If the response overflows the internal
  122. // read buffer, switch to a dynamically
  123. // allocated flat buffer.
  124. d_.fb.commit(net::buffer_copy(
  125. d_.fb.prepare(impl.rd_buf.size()),
  126. impl.rd_buf.data()));
  127. impl.rd_buf.clear();
  128. BOOST_ASIO_CORO_YIELD
  129. {
  130. BOOST_ASIO_HANDLER_LOCATION((
  131. __FILE__, __LINE__,
  132. "websocket::async_handshake"));
  133. http::async_read(impl.stream(),
  134. d_.fb, d_.p, std::move(*this));
  135. }
  136. if(! ec)
  137. {
  138. // Copy any leftovers back into the read
  139. // buffer, since this represents websocket
  140. // frame data.
  141. if(d_.fb.size() <= impl.rd_buf.capacity())
  142. {
  143. impl.rd_buf.commit(net::buffer_copy(
  144. impl.rd_buf.prepare(d_.fb.size()),
  145. d_.fb.data()));
  146. }
  147. else
  148. {
  149. BOOST_BEAST_ASSIGN_EC(ec, http::error::buffer_overflow);
  150. }
  151. }
  152. // Do this before the upcall
  153. d_.fb.clear();
  154. }
  155. if(impl.check_stop_now(ec))
  156. goto upcall;
  157. // success
  158. impl.reset_idle();
  159. impl.on_response(d_.p.get(), key_, ec);
  160. if(res_p_)
  161. swap(d_.p.get(), *res_p_);
  162. upcall:
  163. this->complete(cont ,ec);
  164. }
  165. }
  166. };
  167. template<class NextLayer, bool deflateSupported>
  168. struct stream<NextLayer, deflateSupported>::
  169. run_handshake_op
  170. {
  171. boost::shared_ptr<impl_type> const& self;
  172. using executor_type = typename stream::executor_type;
  173. executor_type
  174. get_executor() const noexcept
  175. {
  176. return self->stream().get_executor();
  177. }
  178. template<class HandshakeHandler>
  179. void operator()(
  180. HandshakeHandler&& h,
  181. request_type&& req,
  182. detail::sec_ws_key_type key,
  183. response_type* res_p)
  184. {
  185. // If you get an error on the following line it means
  186. // that your handler does not meet the documented type
  187. // requirements for the handler.
  188. static_assert(
  189. beast::detail::is_invocable<HandshakeHandler,
  190. void(error_code)>::value,
  191. "HandshakeHandler type requirements not met");
  192. handshake_op<
  193. typename std::decay<HandshakeHandler>::type>(
  194. std::forward<HandshakeHandler>(h),
  195. self, std::move(req), key, res_p);
  196. }
  197. };
  198. //------------------------------------------------------------------------------
  199. template<class NextLayer, bool deflateSupported>
  200. template<class RequestDecorator>
  201. void
  202. stream<NextLayer, deflateSupported>::
  203. do_handshake(
  204. response_type* res_p,
  205. string_view host,
  206. string_view target,
  207. RequestDecorator const& decorator,
  208. error_code& ec)
  209. {
  210. if(res_p)
  211. res_p->result(http::status::internal_server_error);
  212. auto& impl = *impl_;
  213. impl.change_status(status::handshake);
  214. impl.reset();
  215. detail::sec_ws_key_type key;
  216. {
  217. auto const req = impl.build_request(
  218. key, host, target, decorator);
  219. impl.do_pmd_config(req);
  220. http::write(impl.stream(), req, ec);
  221. }
  222. if(impl.check_stop_now(ec))
  223. return;
  224. http::response_parser<
  225. typename response_type::body_type> p;
  226. http::read(next_layer(), impl.rd_buf, p, ec);
  227. if(ec == http::error::buffer_overflow)
  228. {
  229. // If the response overflows the internal
  230. // read buffer, switch to a dynamically
  231. // allocated flat buffer.
  232. flat_buffer fb;
  233. fb.commit(net::buffer_copy(
  234. fb.prepare(impl.rd_buf.size()),
  235. impl.rd_buf.data()));
  236. impl.rd_buf.clear();
  237. http::read(next_layer(), fb, p, ec);;
  238. if(! ec)
  239. {
  240. // Copy any leftovers back into the read
  241. // buffer, since this represents websocket
  242. // frame data.
  243. if(fb.size() <= impl.rd_buf.capacity())
  244. {
  245. impl.rd_buf.commit(net::buffer_copy(
  246. impl.rd_buf.prepare(fb.size()),
  247. fb.data()));
  248. }
  249. else
  250. {
  251. BOOST_BEAST_ASSIGN_EC(ec, http::error::buffer_overflow);
  252. }
  253. }
  254. }
  255. if(impl.check_stop_now(ec))
  256. return;
  257. if (res_p)
  258. {
  259. // If res_p is not null, move parser's response into it.
  260. *res_p = p.release();
  261. }
  262. else
  263. {
  264. // Otherwise point res_p at the response in the parser.
  265. res_p = &p.get();
  266. }
  267. impl.on_response(*res_p, key, ec);
  268. }
  269. //------------------------------------------------------------------------------
  270. template<class NextLayer, bool deflateSupported>
  271. template<BOOST_BEAST_ASYNC_TPARAM1 HandshakeHandler>
  272. BOOST_BEAST_ASYNC_RESULT1(HandshakeHandler)
  273. stream<NextLayer, deflateSupported>::
  274. async_handshake(
  275. string_view host,
  276. string_view target,
  277. HandshakeHandler&& handler)
  278. {
  279. static_assert(is_async_stream<next_layer_type>::value,
  280. "AsyncStream type requirements not met");
  281. detail::sec_ws_key_type key;
  282. auto req = impl_->build_request(
  283. key, host, target, &default_decorate_req);
  284. return net::async_initiate<
  285. HandshakeHandler,
  286. void(error_code)>(
  287. run_handshake_op{impl_},
  288. handler,
  289. std::move(req),
  290. key,
  291. nullptr);
  292. }
  293. template<class NextLayer, bool deflateSupported>
  294. template<BOOST_BEAST_ASYNC_TPARAM1 HandshakeHandler>
  295. BOOST_BEAST_ASYNC_RESULT1(HandshakeHandler)
  296. stream<NextLayer, deflateSupported>::
  297. async_handshake(
  298. response_type& res,
  299. string_view host,
  300. string_view target,
  301. HandshakeHandler&& handler)
  302. {
  303. static_assert(is_async_stream<next_layer_type>::value,
  304. "AsyncStream type requirements not met");
  305. detail::sec_ws_key_type key;
  306. auto req = impl_->build_request(
  307. key, host, target, &default_decorate_req);
  308. return net::async_initiate<
  309. HandshakeHandler,
  310. void(error_code)>(
  311. run_handshake_op{impl_},
  312. handler,
  313. std::move(req),
  314. key,
  315. &res);
  316. }
  317. template<class NextLayer, bool deflateSupported>
  318. void
  319. stream<NextLayer, deflateSupported>::
  320. handshake(string_view host,
  321. string_view target)
  322. {
  323. static_assert(is_sync_stream<next_layer_type>::value,
  324. "SyncStream type requirements not met");
  325. error_code ec;
  326. handshake(
  327. host, target, ec);
  328. if(ec)
  329. BOOST_THROW_EXCEPTION(system_error{ec});
  330. }
  331. template<class NextLayer, bool deflateSupported>
  332. void
  333. stream<NextLayer, deflateSupported>::
  334. handshake(response_type& res,
  335. string_view host,
  336. string_view target)
  337. {
  338. static_assert(is_sync_stream<next_layer_type>::value,
  339. "SyncStream type requirements not met");
  340. error_code ec;
  341. handshake(res, host, target, ec);
  342. if(ec)
  343. BOOST_THROW_EXCEPTION(system_error{ec});
  344. }
  345. template<class NextLayer, bool deflateSupported>
  346. void
  347. stream<NextLayer, deflateSupported>::
  348. handshake(string_view host,
  349. string_view target, error_code& ec)
  350. {
  351. static_assert(is_sync_stream<next_layer_type>::value,
  352. "SyncStream type requirements not met");
  353. do_handshake(nullptr,
  354. host, target, &default_decorate_req, ec);
  355. }
  356. template<class NextLayer, bool deflateSupported>
  357. void
  358. stream<NextLayer, deflateSupported>::
  359. handshake(response_type& res,
  360. string_view host,
  361. string_view target,
  362. error_code& ec)
  363. {
  364. static_assert(is_sync_stream<next_layer_type>::value,
  365. "SyncStream type requirements not met");
  366. do_handshake(&res,
  367. host, target, &default_decorate_req, ec);
  368. }
  369. } // websocket
  370. } // beast
  371. } // boost
  372. #endif