accept.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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_ACCEPT_IPP
  10. #define BOOST_BEAST_WEBSOCKET_IMPL_ACCEPT_IPP
  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/parser.hpp>
  15. #include <boost/beast/http/read.hpp>
  16. #include <boost/beast/http/string_body.hpp>
  17. #include <boost/beast/http/write.hpp>
  18. #include <boost/beast/core/async_base.hpp>
  19. #include <boost/beast/core/buffer_traits.hpp>
  20. #include <boost/beast/core/stream_traits.hpp>
  21. #include <boost/beast/core/detail/buffer.hpp>
  22. #include <boost/beast/version.hpp>
  23. #include <boost/asio/coroutine.hpp>
  24. #include <boost/assert.hpp>
  25. #include <boost/throw_exception.hpp>
  26. #include <memory>
  27. #include <type_traits>
  28. namespace boost {
  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.contains(http::field::server))
  72. res.set(http::field::server,
  73. string_view(BOOST_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.contains(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. boost::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. boost::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. boost::ignore_unused(bytes_transferred);
  200. auto sp = wp_.lock();
  201. if(! sp)
  202. {
  203. BOOST_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  204. return this->complete(cont, ec);
  205. }
  206. auto& impl = *sp;
  207. BOOST_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. BOOST_ASIO_CORO_YIELD
  214. {
  215. BOOST_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. BOOST_ASIO_CORO_YIELD
  222. {
  223. BOOST_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. BOOST_BEAST_ASSIGN_EC(ec, result_);
  234. BOOST_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. boost::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. boost::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. impl.reset();
  280. error_code ec;
  281. auto const mb =
  282. beast::detail::dynamic_buffer_prepare(
  283. impl.rd_buf, buffer_bytes(buffers),
  284. ec, error::buffer_overflow);
  285. if(! ec)
  286. impl.rd_buf.commit(
  287. net::buffer_copy(*mb, buffers));
  288. (*this)(ec);
  289. }
  290. void operator()(
  291. error_code ec = {},
  292. std::size_t bytes_transferred = 0,
  293. bool cont = true)
  294. {
  295. boost::ignore_unused(bytes_transferred);
  296. auto sp = wp_.lock();
  297. if(! sp)
  298. {
  299. BOOST_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  300. return this->complete(cont, ec);
  301. }
  302. auto& impl = *sp;
  303. BOOST_ASIO_CORO_REENTER(*this)
  304. {
  305. impl.change_status(status::handshake);
  306. impl.update_timer(this->get_executor());
  307. // The constructor could have set ec
  308. if(ec)
  309. goto upcall;
  310. BOOST_ASIO_CORO_YIELD
  311. {
  312. BOOST_ASIO_HANDLER_LOCATION((
  313. __FILE__, __LINE__,
  314. "websocket::async_accept"));
  315. http::async_read(impl.stream(),
  316. impl.rd_buf, p_, std::move(*this));
  317. }
  318. if(ec == http::error::end_of_stream)
  319. {
  320. BOOST_BEAST_ASSIGN_EC(ec, error::closed);
  321. }
  322. if(impl.check_stop_now(ec))
  323. goto upcall;
  324. {
  325. // Arguments from our state must be
  326. // moved to the stack before releasing
  327. // the handler.
  328. auto const req = p_.release();
  329. auto const decorator = d_;
  330. response_op<Handler>(
  331. this->release_handler(),
  332. sp, req, decorator, true);
  333. return;
  334. }
  335. upcall:
  336. this->complete(cont, ec);
  337. }
  338. }
  339. };
  340. template<class NextLayer, bool deflateSupported>
  341. struct stream<NextLayer, deflateSupported>::
  342. run_response_op
  343. {
  344. boost::shared_ptr<impl_type> const& self;
  345. using executor_type = typename stream::executor_type;
  346. executor_type
  347. get_executor() const noexcept
  348. {
  349. return self->stream().get_executor();
  350. }
  351. template<
  352. class AcceptHandler,
  353. class Body, class Allocator,
  354. class Decorator>
  355. void
  356. operator()(
  357. AcceptHandler&& h,
  358. http::request<Body,
  359. http::basic_fields<Allocator>> const* m,
  360. Decorator const& d)
  361. {
  362. // If you get an error on the following line it means
  363. // that your handler does not meet the documented type
  364. // requirements for the handler.
  365. static_assert(
  366. beast::detail::is_invocable<AcceptHandler,
  367. void(error_code)>::value,
  368. "AcceptHandler type requirements not met");
  369. response_op<
  370. typename std::decay<AcceptHandler>::type>(
  371. std::forward<AcceptHandler>(h), self, *m, d);
  372. }
  373. };
  374. template<class NextLayer, bool deflateSupported>
  375. struct stream<NextLayer, deflateSupported>::
  376. run_accept_op
  377. {
  378. boost::shared_ptr<impl_type> const& self;
  379. using executor_type = typename stream::executor_type;
  380. executor_type
  381. get_executor() const noexcept
  382. {
  383. return self->stream().get_executor();
  384. }
  385. template<
  386. class AcceptHandler,
  387. class Decorator,
  388. class Buffers>
  389. void
  390. operator()(
  391. AcceptHandler&& h,
  392. Decorator const& d,
  393. Buffers const& b)
  394. {
  395. // If you get an error on the following line it means
  396. // that your handler does not meet the documented type
  397. // requirements for the handler.
  398. static_assert(
  399. beast::detail::is_invocable<AcceptHandler,
  400. void(error_code)>::value,
  401. "AcceptHandler type requirements not met");
  402. accept_op<
  403. typename std::decay<AcceptHandler>::type,
  404. Decorator>(
  405. std::forward<AcceptHandler>(h),
  406. self,
  407. d,
  408. b);
  409. }
  410. };
  411. //------------------------------------------------------------------------------
  412. template<class NextLayer, bool deflateSupported>
  413. template<class Body, class Allocator,
  414. class Decorator>
  415. void
  416. stream<NextLayer, deflateSupported>::
  417. do_accept(
  418. http::request<Body,
  419. http::basic_fields<Allocator>> const& req,
  420. Decorator const& decorator,
  421. error_code& ec)
  422. {
  423. impl_->change_status(status::handshake);
  424. error_code result;
  425. auto const res = impl_->build_response(req, decorator, result);
  426. auto itr = req.find(http::field::expect);
  427. if (itr != req.end() && iequals(itr->value(), "100-continue")) // do
  428. {
  429. http::response<http::empty_body> res_100;
  430. res_100.version(res.version());
  431. res_100.set(http::field::server, res[http::field::server]);
  432. res_100.result(http::status::continue_);
  433. res_100.prepare_payload();
  434. http::write(impl_->stream(), res_100, ec);
  435. if (ec)
  436. return;
  437. }
  438. http::write(impl_->stream(), res, ec);
  439. if(ec)
  440. return;
  441. BOOST_BEAST_ASSIGN_EC(ec, result);
  442. if(ec)
  443. {
  444. // VFALCO TODO Respect keep alive setting, perform
  445. // teardown if Connection: close.
  446. return;
  447. }
  448. impl_->do_pmd_config(res);
  449. impl_->open(role_type::server);
  450. }
  451. template<class NextLayer, bool deflateSupported>
  452. template<class Buffers, class Decorator>
  453. void
  454. stream<NextLayer, deflateSupported>::
  455. do_accept(
  456. Buffers const& buffers,
  457. Decorator const& decorator,
  458. error_code& ec)
  459. {
  460. impl_->reset();
  461. auto const mb =
  462. beast::detail::dynamic_buffer_prepare(
  463. impl_->rd_buf, buffer_bytes(buffers), ec,
  464. error::buffer_overflow);
  465. if(ec)
  466. return;
  467. impl_->rd_buf.commit(net::buffer_copy(*mb, buffers));
  468. http::request_parser<http::empty_body> p;
  469. http::read(next_layer(), impl_->rd_buf, p, ec);
  470. if(ec == http::error::end_of_stream)
  471. {
  472. BOOST_BEAST_ASSIGN_EC(ec, error::closed);
  473. }
  474. if(ec)
  475. return;
  476. do_accept(p.get(), decorator, ec);
  477. }
  478. //------------------------------------------------------------------------------
  479. template<class NextLayer, bool deflateSupported>
  480. void
  481. stream<NextLayer, deflateSupported>::
  482. accept()
  483. {
  484. static_assert(is_sync_stream<next_layer_type>::value,
  485. "SyncStream type requirements not met");
  486. error_code ec;
  487. accept(ec);
  488. if(ec)
  489. BOOST_THROW_EXCEPTION(system_error{ec});
  490. }
  491. template<class NextLayer, bool deflateSupported>
  492. void
  493. stream<NextLayer, deflateSupported>::
  494. accept(error_code& ec)
  495. {
  496. static_assert(is_sync_stream<next_layer_type>::value,
  497. "SyncStream type requirements not met");
  498. do_accept(
  499. net::const_buffer{},
  500. &default_decorate_res, ec);
  501. }
  502. template<class NextLayer, bool deflateSupported>
  503. template<class ConstBufferSequence>
  504. typename std::enable_if<! http::detail::is_header<
  505. ConstBufferSequence>::value>::type
  506. stream<NextLayer, deflateSupported>::
  507. accept(ConstBufferSequence const& buffers)
  508. {
  509. static_assert(is_sync_stream<next_layer_type>::value,
  510. "SyncStream type requirements not met");
  511. static_assert(net::is_const_buffer_sequence<
  512. ConstBufferSequence>::value,
  513. "ConstBufferSequence type requirements not met");
  514. error_code ec;
  515. accept(buffers, ec);
  516. if(ec)
  517. BOOST_THROW_EXCEPTION(system_error{ec});
  518. }
  519. template<class NextLayer, bool deflateSupported>
  520. template<class ConstBufferSequence>
  521. typename std::enable_if<! http::detail::is_header<
  522. ConstBufferSequence>::value>::type
  523. stream<NextLayer, deflateSupported>::
  524. accept(
  525. ConstBufferSequence const& buffers, error_code& ec)
  526. {
  527. static_assert(is_sync_stream<next_layer_type>::value,
  528. "SyncStream type requirements not met");
  529. static_assert(net::is_const_buffer_sequence<
  530. ConstBufferSequence>::value,
  531. "ConstBufferSequence type requirements not met");
  532. do_accept(buffers, &default_decorate_res, ec);
  533. }
  534. template<class NextLayer, bool deflateSupported>
  535. template<class Body, class Allocator>
  536. void
  537. stream<NextLayer, deflateSupported>::
  538. accept(
  539. http::request<Body,
  540. http::basic_fields<Allocator>> const& req)
  541. {
  542. static_assert(is_sync_stream<next_layer_type>::value,
  543. "SyncStream type requirements not met");
  544. error_code ec;
  545. accept(req, ec);
  546. if(ec)
  547. BOOST_THROW_EXCEPTION(system_error{ec});
  548. }
  549. template<class NextLayer, bool deflateSupported>
  550. template<class Body, class Allocator>
  551. void
  552. stream<NextLayer, deflateSupported>::
  553. accept(
  554. http::request<Body,
  555. http::basic_fields<Allocator>> const& req,
  556. error_code& ec)
  557. {
  558. static_assert(is_sync_stream<next_layer_type>::value,
  559. "SyncStream type requirements not met");
  560. impl_->reset();
  561. do_accept(req, &default_decorate_res, ec);
  562. }
  563. //------------------------------------------------------------------------------
  564. template<class NextLayer, bool deflateSupported>
  565. template<
  566. BOOST_BEAST_ASYNC_TPARAM1 AcceptHandler>
  567. BOOST_BEAST_ASYNC_RESULT1(AcceptHandler)
  568. stream<NextLayer, deflateSupported>::
  569. async_accept(
  570. AcceptHandler&& handler,
  571. typename std::enable_if<
  572. ! net::is_const_buffer_sequence<
  573. AcceptHandler>::value>::type*
  574. )
  575. {
  576. static_assert(is_async_stream<next_layer_type>::value,
  577. "AsyncStream type requirements not met");
  578. return net::async_initiate<
  579. AcceptHandler,
  580. void(error_code)>(
  581. run_accept_op{impl_},
  582. handler,
  583. &default_decorate_res,
  584. net::const_buffer{});
  585. }
  586. template<class NextLayer, bool deflateSupported>
  587. template<
  588. class ConstBufferSequence,
  589. BOOST_BEAST_ASYNC_TPARAM1 AcceptHandler>
  590. BOOST_BEAST_ASYNC_RESULT1(AcceptHandler)
  591. stream<NextLayer, deflateSupported>::
  592. async_accept(
  593. ConstBufferSequence const& buffers,
  594. AcceptHandler&& handler,
  595. typename std::enable_if<
  596. net::is_const_buffer_sequence<
  597. ConstBufferSequence>::value>::type*,
  598. typename std::enable_if<
  599. ! http::detail::is_header<
  600. ConstBufferSequence>::value>::type*
  601. )
  602. {
  603. static_assert(is_async_stream<next_layer_type>::value,
  604. "AsyncStream type requirements not met");
  605. static_assert(net::is_const_buffer_sequence<
  606. ConstBufferSequence>::value,
  607. "ConstBufferSequence type requirements not met");
  608. return net::async_initiate<
  609. AcceptHandler,
  610. void(error_code)>(
  611. run_accept_op{impl_},
  612. handler,
  613. &default_decorate_res,
  614. buffers);
  615. }
  616. template<class NextLayer, bool deflateSupported>
  617. template<
  618. class Body, class Allocator,
  619. BOOST_BEAST_ASYNC_TPARAM1 AcceptHandler>
  620. BOOST_BEAST_ASYNC_RESULT1(AcceptHandler)
  621. stream<NextLayer, deflateSupported>::
  622. async_accept(
  623. http::request<Body, http::basic_fields<Allocator>> const& req,
  624. AcceptHandler&& handler)
  625. {
  626. static_assert(is_async_stream<next_layer_type>::value,
  627. "AsyncStream type requirements not met");
  628. return net::async_initiate<
  629. AcceptHandler,
  630. void(error_code)>(
  631. run_response_op{impl_},
  632. handler,
  633. &req,
  634. &default_decorate_res);
  635. }
  636. } // websocket
  637. } // beast
  638. } // boost
  639. #endif