accept.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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 BHO_BEAST_WEBSOCKET_IMPL_ACCEPT_IPP
  10. #define BHO_BEAST_WEBSOCKET_IMPL_ACCEPT_IPP
  11. #include <asio2/bho/beast/websocket/impl/stream_impl.hpp>
  12. #include <asio2/bho/beast/websocket/detail/type_traits.hpp>
  13. #include <asio2/bho/beast/http/empty_body.hpp>
  14. #include <asio2/bho/beast/http/parser.hpp>
  15. #include <asio2/bho/beast/http/read.hpp>
  16. #include <asio2/bho/beast/http/string_body.hpp>
  17. #include <asio2/bho/beast/http/write.hpp>
  18. #include <asio2/bho/beast/core/async_base.hpp>
  19. #include <asio2/bho/beast/core/buffer_traits.hpp>
  20. #include <asio2/bho/beast/core/stream_traits.hpp>
  21. #include <asio2/bho/beast/core/detail/buffer.hpp>
  22. #include <asio2/bho/beast/version.hpp>
  23. #include <asio/coroutine.hpp>
  24. #include <asio2/bho/assert.hpp>
  25. #include <asio2/bho/throw_exception.hpp>
  26. #include <memory>
  27. #include <type_traits>
  28. namespace bho {
  29. namespace beast {
  30. namespace websocket {
  31. //------------------------------------------------------------------------------
  32. namespace detail {
  33. template<class Body, class Allocator>
  34. void
  35. impl_base<true>::
  36. build_response_pmd(
  37. http::response<http::string_body>& res,
  38. http::request<Body,
  39. http::basic_fields<Allocator>> const& req)
  40. {
  41. pmd_offer offer;
  42. pmd_offer unused;
  43. pmd_read(offer, req);
  44. pmd_negotiate(res, unused, offer, pmd_opts_);
  45. }
  46. template<class Body, class Allocator>
  47. void
  48. impl_base<false>::
  49. build_response_pmd(
  50. http::response<http::string_body>&,
  51. http::request<Body,
  52. http::basic_fields<Allocator>> const&)
  53. {
  54. }
  55. } // detail
  56. template<class NextLayer, bool deflateSupported>
  57. template<class Body, class Allocator, class Decorator>
  58. response_type
  59. stream<NextLayer, deflateSupported>::impl_type::
  60. build_response(
  61. http::request<Body,
  62. http::basic_fields<Allocator>> const& req,
  63. Decorator const& decorator,
  64. error_code& result)
  65. {
  66. auto const decorate =
  67. [this, &decorator](response_type& res)
  68. {
  69. decorator_opt(res);
  70. decorator(res);
  71. if(! res.count(http::field::server))
  72. res.set(http::field::server,
  73. string_view(BHO_BEAST_VERSION_STRING));
  74. };
  75. auto err =
  76. [&](error e)
  77. {
  78. result = e;
  79. response_type res;
  80. res.version(req.version());
  81. res.result(http::status::bad_request);
  82. res.body() = result.message();
  83. res.prepare_payload();
  84. decorate(res);
  85. return res;
  86. };
  87. if(req.version() != 11)
  88. return err(error::bad_http_version);
  89. if(req.method() != http::verb::get)
  90. return err(error::bad_method);
  91. if(! req.count(http::field::host))
  92. return err(error::no_host);
  93. {
  94. auto const it = req.find(http::field::connection);
  95. if(it == req.end())
  96. return err(error::no_connection);
  97. if(! http::token_list{it->value()}.exists("upgrade"))
  98. return err(error::no_connection_upgrade);
  99. }
  100. {
  101. auto const it = req.find(http::field::upgrade);
  102. if(it == req.end())
  103. return err(error::no_upgrade);
  104. if(! http::token_list{it->value()}.exists("websocket"))
  105. return err(error::no_upgrade_websocket);
  106. }
  107. string_view key;
  108. {
  109. auto const it = req.find(http::field::sec_websocket_key);
  110. if(it == req.end())
  111. return err(error::no_sec_key);
  112. key = it->value();
  113. if(key.size() > detail::sec_ws_key_type::static_capacity)
  114. return err(error::bad_sec_key);
  115. }
  116. {
  117. auto const it = req.find(http::field::sec_websocket_version);
  118. if(it == req.end())
  119. return err(error::no_sec_version);
  120. if(it->value() != "13")
  121. {
  122. response_type res;
  123. res.result(http::status::upgrade_required);
  124. res.version(req.version());
  125. res.set(http::field::sec_websocket_version, "13");
  126. result = error::bad_sec_version;
  127. res.body() = result.message();
  128. res.prepare_payload();
  129. decorate(res);
  130. return res;
  131. }
  132. }
  133. response_type res;
  134. res.result(http::status::switching_protocols);
  135. res.version(req.version());
  136. res.set(http::field::upgrade, "websocket");
  137. res.set(http::field::connection, "Upgrade");
  138. {
  139. detail::sec_ws_accept_type acc;
  140. detail::make_sec_ws_accept(acc, key);
  141. res.set(http::field::sec_websocket_accept, to_string_view(acc));
  142. }
  143. this->build_response_pmd(res, req);
  144. decorate(res);
  145. result = {};
  146. return res;
  147. }
  148. //------------------------------------------------------------------------------
  149. /** Respond to an HTTP request
  150. */
  151. template<class NextLayer, bool deflateSupported>
  152. template<class Handler>
  153. class stream<NextLayer, deflateSupported>::response_op
  154. : public beast::stable_async_base<
  155. Handler, beast::executor_type<stream>>
  156. , public asio::coroutine
  157. {
  158. std::weak_ptr<impl_type> wp_;
  159. error_code result_; // must come before res_
  160. response_type& res_;
  161. http::response<http::empty_body> res_100_;
  162. bool needs_res_100_{false};
  163. public:
  164. template<
  165. class Handler_,
  166. class Body, class Allocator,
  167. class Decorator>
  168. response_op(
  169. Handler_&& h,
  170. std::shared_ptr<impl_type> const& sp,
  171. http::request<Body,
  172. http::basic_fields<Allocator>> const& req,
  173. Decorator const& decorator,
  174. bool cont = false)
  175. : stable_async_base<Handler,
  176. beast::executor_type<stream>>(
  177. std::forward<Handler_>(h),
  178. sp->stream().get_executor())
  179. , wp_(sp)
  180. , res_(beast::allocate_stable<response_type>(*this,
  181. sp->build_response(req, decorator, result_)))
  182. {
  183. auto itr = req.find(http::field::expect);
  184. if (itr != req.end() && iequals(itr->value(), "100-continue")) // do
  185. {
  186. res_100_.version(res_.version());
  187. res_100_.set(http::field::server, res_[http::field::server]);
  188. res_100_.result(http::status::continue_);
  189. res_100_.prepare_payload();
  190. needs_res_100_ = true;
  191. }
  192. (*this)({}, 0, cont);
  193. }
  194. void operator()(
  195. error_code ec = {},
  196. std::size_t bytes_transferred = 0,
  197. bool cont = true)
  198. {
  199. bho::ignore_unused(bytes_transferred);
  200. auto sp = wp_.lock();
  201. if(! sp)
  202. {
  203. BHO_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  204. return this->complete(cont, ec);
  205. }
  206. auto& impl = *sp;
  207. ASIO_CORO_REENTER(*this)
  208. {
  209. impl.change_status(status::handshake);
  210. impl.update_timer(this->get_executor());
  211. if (needs_res_100_)
  212. {
  213. ASIO_CORO_YIELD
  214. {
  215. ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "websocket::async_accept"));
  216. http::async_write(
  217. impl.stream(), res_100_, std::move(*this));
  218. }
  219. }
  220. // Send response
  221. ASIO_CORO_YIELD
  222. {
  223. ASIO_HANDLER_LOCATION((
  224. __FILE__, __LINE__,
  225. "websocket::async_accept"));
  226. http::async_write(
  227. impl.stream(), res_, std::move(*this));
  228. }
  229. if(impl.check_stop_now(ec))
  230. goto upcall;
  231. if(! ec)
  232. {
  233. BHO_BEAST_ASSIGN_EC(ec, result_);
  234. BHO_BEAST_ASSIGN_EC(ec, result_);
  235. }
  236. if(! ec)
  237. {
  238. impl.do_pmd_config(res_);
  239. impl.open(role_type::server);
  240. }
  241. upcall:
  242. this->complete(cont, ec);
  243. }
  244. }
  245. };
  246. //------------------------------------------------------------------------------
  247. // read and respond to an upgrade request
  248. //
  249. // Cancellation: the async_accept cancellation can be terminal
  250. // because it will just interrupt the reading of the header.
  251. //
  252. template<class NextLayer, bool deflateSupported>
  253. template<class Handler, class Decorator>
  254. class stream<NextLayer, deflateSupported>::accept_op
  255. : public beast::stable_async_base<
  256. Handler, beast::executor_type<stream>>
  257. , public asio::coroutine
  258. {
  259. std::weak_ptr<impl_type> wp_;
  260. http::request_parser<http::empty_body>& p_;
  261. Decorator d_;
  262. public:
  263. template<class Handler_, class Buffers>
  264. accept_op(
  265. Handler_&& h,
  266. std::shared_ptr<impl_type> const& sp,
  267. Decorator const& decorator,
  268. Buffers const& buffers)
  269. : stable_async_base<Handler,
  270. beast::executor_type<stream>>(
  271. std::forward<Handler_>(h),
  272. sp->stream().get_executor())
  273. , wp_(sp)
  274. , p_(beast::allocate_stable<
  275. http::request_parser<http::empty_body>>(*this))
  276. , d_(decorator)
  277. {
  278. auto& impl = *sp;
  279. error_code ec;
  280. auto const mb =
  281. beast::detail::dynamic_buffer_prepare(
  282. impl.rd_buf, buffer_bytes(buffers),
  283. ec, error::buffer_overflow);
  284. if(! ec)
  285. impl.rd_buf.commit(
  286. net::buffer_copy(*mb, buffers));
  287. (*this)(ec);
  288. }
  289. void operator()(
  290. error_code ec = {},
  291. std::size_t bytes_transferred = 0,
  292. bool cont = true)
  293. {
  294. bho::ignore_unused(bytes_transferred);
  295. auto sp = wp_.lock();
  296. if(! sp)
  297. {
  298. BHO_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  299. return this->complete(cont, ec);
  300. }
  301. auto& impl = *sp;
  302. ASIO_CORO_REENTER(*this)
  303. {
  304. impl.change_status(status::handshake);
  305. impl.update_timer(this->get_executor());
  306. // The constructor could have set ec
  307. if(ec)
  308. goto upcall;
  309. ASIO_CORO_YIELD
  310. {
  311. ASIO_HANDLER_LOCATION((
  312. __FILE__, __LINE__,
  313. "websocket::async_accept"));
  314. http::async_read(impl.stream(),
  315. impl.rd_buf, p_, std::move(*this));
  316. }
  317. if(ec == http::error::end_of_stream)
  318. {
  319. BHO_BEAST_ASSIGN_EC(ec, error::closed);
  320. }
  321. if(impl.check_stop_now(ec))
  322. goto upcall;
  323. {
  324. // Arguments from our state must be
  325. // moved to the stack before releasing
  326. // the handler.
  327. auto const req = p_.release();
  328. auto const decorator = d_;
  329. response_op<Handler>(
  330. this->release_handler(),
  331. sp, req, decorator, true);
  332. return;
  333. }
  334. upcall:
  335. this->complete(cont, ec);
  336. }
  337. }
  338. };
  339. template<class NextLayer, bool deflateSupported>
  340. struct stream<NextLayer, deflateSupported>::
  341. run_response_op
  342. {
  343. template<
  344. class AcceptHandler,
  345. class Body, class Allocator,
  346. class Decorator>
  347. void
  348. operator()(
  349. AcceptHandler&& h,
  350. std::shared_ptr<impl_type> const& sp,
  351. http::request<Body,
  352. http::basic_fields<Allocator>> const* m,
  353. Decorator const& d)
  354. {
  355. // If you get an error on the following line it means
  356. // that your handler does not meet the documented type
  357. // requirements for the handler.
  358. static_assert(
  359. beast::detail::is_invocable<AcceptHandler,
  360. void(error_code)>::value,
  361. "AcceptHandler type requirements not met");
  362. response_op<
  363. typename std::decay<AcceptHandler>::type>(
  364. std::forward<AcceptHandler>(h), sp, *m, d);
  365. }
  366. };
  367. template<class NextLayer, bool deflateSupported>
  368. struct stream<NextLayer, deflateSupported>::
  369. run_accept_op
  370. {
  371. template<
  372. class AcceptHandler,
  373. class Decorator,
  374. class Buffers>
  375. void
  376. operator()(
  377. AcceptHandler&& h,
  378. std::shared_ptr<impl_type> const& sp,
  379. Decorator const& d,
  380. Buffers const& b)
  381. {
  382. // If you get an error on the following line it means
  383. // that your handler does not meet the documented type
  384. // requirements for the handler.
  385. static_assert(
  386. beast::detail::is_invocable<AcceptHandler,
  387. void(error_code)>::value,
  388. "AcceptHandler type requirements not met");
  389. accept_op<
  390. typename std::decay<AcceptHandler>::type,
  391. Decorator>(
  392. std::forward<AcceptHandler>(h),
  393. sp,
  394. d,
  395. b);
  396. }
  397. };
  398. //------------------------------------------------------------------------------
  399. template<class NextLayer, bool deflateSupported>
  400. template<class Body, class Allocator,
  401. class Decorator>
  402. void
  403. stream<NextLayer, deflateSupported>::
  404. do_accept(
  405. http::request<Body,
  406. http::basic_fields<Allocator>> const& req,
  407. Decorator const& decorator,
  408. error_code& ec)
  409. {
  410. impl_->change_status(status::handshake);
  411. error_code result;
  412. auto const res = impl_->build_response(req, decorator, result);
  413. auto itr = req.find(http::field::expect);
  414. if (itr != req.end() && iequals(itr->value(), "100-continue")) // do
  415. {
  416. http::response<http::empty_body> res_100;
  417. res_100.version(res.version());
  418. res_100.set(http::field::server, res[http::field::server]);
  419. res_100.result(http::status::continue_);
  420. res_100.prepare_payload();
  421. http::write(impl_->stream(), res_100, ec);
  422. if (ec)
  423. return;
  424. }
  425. http::write(impl_->stream(), res, ec);
  426. if(ec)
  427. return;
  428. BHO_BEAST_ASSIGN_EC(ec, result);
  429. if(ec)
  430. {
  431. // VFALCO TODO Respect keep alive setting, perform
  432. // teardown if Connection: close.
  433. return;
  434. }
  435. impl_->do_pmd_config(res);
  436. impl_->open(role_type::server);
  437. }
  438. template<class NextLayer, bool deflateSupported>
  439. template<class Buffers, class Decorator>
  440. void
  441. stream<NextLayer, deflateSupported>::
  442. do_accept(
  443. Buffers const& buffers,
  444. Decorator const& decorator,
  445. error_code& ec)
  446. {
  447. impl_->reset();
  448. auto const mb =
  449. beast::detail::dynamic_buffer_prepare(
  450. impl_->rd_buf, buffer_bytes(buffers), ec,
  451. error::buffer_overflow);
  452. if(ec)
  453. return;
  454. impl_->rd_buf.commit(net::buffer_copy(*mb, buffers));
  455. http::request_parser<http::empty_body> p;
  456. http::read(next_layer(), impl_->rd_buf, p, ec);
  457. if(ec == http::error::end_of_stream)
  458. {
  459. BHO_BEAST_ASSIGN_EC(ec, error::closed);
  460. }
  461. if(ec)
  462. return;
  463. do_accept(p.get(), decorator, ec);
  464. }
  465. //------------------------------------------------------------------------------
  466. template<class NextLayer, bool deflateSupported>
  467. void
  468. stream<NextLayer, deflateSupported>::
  469. accept()
  470. {
  471. static_assert(is_sync_stream<next_layer_type>::value,
  472. "SyncStream type requirements not met");
  473. error_code ec;
  474. accept(ec);
  475. if(ec)
  476. BHO_THROW_EXCEPTION(system_error{ec});
  477. }
  478. template<class NextLayer, bool deflateSupported>
  479. void
  480. stream<NextLayer, deflateSupported>::
  481. accept(error_code& ec)
  482. {
  483. static_assert(is_sync_stream<next_layer_type>::value,
  484. "SyncStream type requirements not met");
  485. do_accept(
  486. net::const_buffer{},
  487. &default_decorate_res, ec);
  488. }
  489. template<class NextLayer, bool deflateSupported>
  490. template<class ConstBufferSequence>
  491. typename std::enable_if<! http::detail::is_header<
  492. ConstBufferSequence>::value>::type
  493. stream<NextLayer, deflateSupported>::
  494. accept(ConstBufferSequence const& buffers)
  495. {
  496. static_assert(is_sync_stream<next_layer_type>::value,
  497. "SyncStream type requirements not met");
  498. static_assert(net::is_const_buffer_sequence<
  499. ConstBufferSequence>::value,
  500. "ConstBufferSequence type requirements not met");
  501. error_code ec;
  502. accept(buffers, ec);
  503. if(ec)
  504. BHO_THROW_EXCEPTION(system_error{ec});
  505. }
  506. template<class NextLayer, bool deflateSupported>
  507. template<class ConstBufferSequence>
  508. typename std::enable_if<! http::detail::is_header<
  509. ConstBufferSequence>::value>::type
  510. stream<NextLayer, deflateSupported>::
  511. accept(
  512. ConstBufferSequence const& buffers, error_code& ec)
  513. {
  514. static_assert(is_sync_stream<next_layer_type>::value,
  515. "SyncStream type requirements not met");
  516. static_assert(net::is_const_buffer_sequence<
  517. ConstBufferSequence>::value,
  518. "ConstBufferSequence type requirements not met");
  519. do_accept(buffers, &default_decorate_res, ec);
  520. }
  521. template<class NextLayer, bool deflateSupported>
  522. template<class Body, class Allocator>
  523. void
  524. stream<NextLayer, deflateSupported>::
  525. accept(
  526. http::request<Body,
  527. http::basic_fields<Allocator>> const& req)
  528. {
  529. static_assert(is_sync_stream<next_layer_type>::value,
  530. "SyncStream type requirements not met");
  531. error_code ec;
  532. accept(req, ec);
  533. if(ec)
  534. BHO_THROW_EXCEPTION(system_error{ec});
  535. }
  536. template<class NextLayer, bool deflateSupported>
  537. template<class Body, class Allocator>
  538. void
  539. stream<NextLayer, deflateSupported>::
  540. accept(
  541. http::request<Body,
  542. http::basic_fields<Allocator>> const& req,
  543. error_code& ec)
  544. {
  545. static_assert(is_sync_stream<next_layer_type>::value,
  546. "SyncStream type requirements not met");
  547. impl_->reset();
  548. do_accept(req, &default_decorate_res, ec);
  549. }
  550. //------------------------------------------------------------------------------
  551. template<class NextLayer, bool deflateSupported>
  552. template<
  553. BHO_BEAST_ASYNC_TPARAM1 AcceptHandler>
  554. BHO_BEAST_ASYNC_RESULT1(AcceptHandler)
  555. stream<NextLayer, deflateSupported>::
  556. async_accept(
  557. AcceptHandler&& handler)
  558. {
  559. static_assert(is_async_stream<next_layer_type>::value,
  560. "AsyncStream type requirements not met");
  561. impl_->reset();
  562. return net::async_initiate<
  563. AcceptHandler,
  564. void(error_code)>(
  565. run_accept_op{},
  566. handler,
  567. impl_,
  568. &default_decorate_res,
  569. net::const_buffer{});
  570. }
  571. template<class NextLayer, bool deflateSupported>
  572. template<
  573. class ConstBufferSequence,
  574. BHO_BEAST_ASYNC_TPARAM1 AcceptHandler>
  575. BHO_BEAST_ASYNC_RESULT1(AcceptHandler)
  576. stream<NextLayer, deflateSupported>::
  577. async_accept(
  578. ConstBufferSequence const& buffers,
  579. AcceptHandler&& handler,
  580. typename std::enable_if<
  581. ! http::detail::is_header<
  582. ConstBufferSequence>::value>::type*
  583. )
  584. {
  585. static_assert(is_async_stream<next_layer_type>::value,
  586. "AsyncStream type requirements not met");
  587. static_assert(net::is_const_buffer_sequence<
  588. ConstBufferSequence>::value,
  589. "ConstBufferSequence type requirements not met");
  590. impl_->reset();
  591. return net::async_initiate<
  592. AcceptHandler,
  593. void(error_code)>(
  594. run_accept_op{},
  595. handler,
  596. impl_,
  597. &default_decorate_res,
  598. buffers);
  599. }
  600. template<class NextLayer, bool deflateSupported>
  601. template<
  602. class Body, class Allocator,
  603. BHO_BEAST_ASYNC_TPARAM1 AcceptHandler>
  604. BHO_BEAST_ASYNC_RESULT1(AcceptHandler)
  605. stream<NextLayer, deflateSupported>::
  606. async_accept(
  607. http::request<Body, http::basic_fields<Allocator>> const& req,
  608. AcceptHandler&& handler)
  609. {
  610. static_assert(is_async_stream<next_layer_type>::value,
  611. "AsyncStream type requirements not met");
  612. impl_->reset();
  613. return net::async_initiate<
  614. AcceptHandler,
  615. void(error_code)>(
  616. run_response_op{},
  617. handler,
  618. impl_,
  619. &req,
  620. &default_decorate_res);
  621. }
  622. } // websocket
  623. } // beast
  624. } // bho
  625. #endif