stream_impl.hpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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_STREAM_IMPL_HPP
  10. #define BOOST_BEAST_WEBSOCKET_IMPL_STREAM_IMPL_HPP
  11. #include <boost/beast/websocket/rfc6455.hpp>
  12. #include <boost/beast/websocket/detail/frame.hpp>
  13. #include <boost/beast/websocket/detail/hybi13.hpp>
  14. #include <boost/beast/websocket/detail/mask.hpp>
  15. #include <boost/beast/websocket/detail/pmd_extension.hpp>
  16. #include <boost/beast/websocket/detail/prng.hpp>
  17. #include <boost/beast/websocket/detail/service.hpp>
  18. #include <boost/beast/websocket/detail/soft_mutex.hpp>
  19. #include <boost/beast/websocket/detail/utf8_checker.hpp>
  20. #include <boost/beast/http/read.hpp>
  21. #include <boost/beast/http/write.hpp>
  22. #include <boost/beast/http/rfc7230.hpp>
  23. #include <boost/beast/core/buffers_cat.hpp>
  24. #include <boost/beast/core/buffers_prefix.hpp>
  25. #include <boost/beast/core/buffers_suffix.hpp>
  26. #include <boost/beast/core/flat_static_buffer.hpp>
  27. #include <boost/beast/core/saved_handler.hpp>
  28. #include <boost/beast/core/static_buffer.hpp>
  29. #include <boost/beast/core/stream_traits.hpp>
  30. #include <boost/beast/core/detail/clamp.hpp>
  31. #include <boost/asio/steady_timer.hpp>
  32. #include <boost/core/empty_value.hpp>
  33. #include <boost/enable_shared_from_this.hpp>
  34. #include <boost/shared_ptr.hpp>
  35. #include <boost/optional.hpp>
  36. namespace boost {
  37. namespace beast {
  38. namespace websocket {
  39. template<
  40. class NextLayer, bool deflateSupported>
  41. struct stream<NextLayer, deflateSupported>::impl_type
  42. : boost::empty_value<NextLayer>
  43. , detail::service::impl_type
  44. , detail::impl_base<deflateSupported>
  45. {
  46. NextLayer& stream() noexcept
  47. {
  48. return this->boost::empty_value<
  49. NextLayer>::get();
  50. }
  51. boost::weak_ptr<impl_type>
  52. weak_from_this()
  53. {
  54. return boost::static_pointer_cast<
  55. impl_type>(this->detail::service::
  56. impl_type::shared_from_this());
  57. }
  58. boost::shared_ptr<impl_type>
  59. shared_this()
  60. {
  61. return boost::static_pointer_cast<
  62. impl_type>(this->detail::service::
  63. impl_type::shared_from_this());
  64. }
  65. using executor_type = typename std::decay<NextLayer>::type::executor_type;
  66. typename net::steady_timer::rebind_executor<executor_type>::other
  67. timer; // used for timeouts
  68. close_reason cr; // set from received close frame
  69. control_cb_type ctrl_cb; // control callback
  70. std::size_t rd_msg_max /* max message size */ = 16 * 1024 * 1024;
  71. std::uint64_t rd_size /* total size of current message so far */ = 0;
  72. std::uint64_t rd_remain /* message frame bytes left in current frame */ = 0;
  73. detail::frame_header rd_fh; // current frame header
  74. detail::prepared_key rd_key; // current stateful mask key
  75. detail::frame_buffer rd_fb; // to write control frames (during reads)
  76. detail::utf8_checker rd_utf8; // to validate utf8
  77. static_buffer<
  78. +tcp_frame_size> rd_buf; // buffer for reads
  79. detail::opcode rd_op /* current message binary or text */ = detail::opcode::text;
  80. bool rd_cont /* `true` if the next frame is a continuation */ = false;
  81. bool rd_done /* set when a message is done */ = true;
  82. bool rd_close /* did we read a close frame? */ = false;
  83. detail::soft_mutex rd_block; // op currently reading
  84. role_type role /* server or client */ = role_type::client;
  85. status status_ /* state of the object */ = status::closed;
  86. detail::soft_mutex wr_block; // op currently writing
  87. bool wr_close /* did we write a close frame? */ = false;
  88. bool wr_cont /* next write is a continuation */ = false;
  89. bool wr_frag /* autofrag the current message */ = false;
  90. bool wr_frag_opt /* autofrag option setting */ = true;
  91. bool wr_compress; /* compress current message */
  92. bool wr_compress_opt /* compress message setting */ = true;
  93. detail::opcode wr_opcode /* message type */ = detail::opcode::text;
  94. std::unique_ptr<
  95. std::uint8_t[]> wr_buf; // write buffer
  96. std::size_t wr_buf_size /* write buffer size (current message) */ = 0;
  97. std::size_t wr_buf_opt /* write buffer size option setting */ = 4096;
  98. detail::fh_buffer wr_fb; // header buffer used for writes
  99. saved_handler op_rd; // paused read op
  100. saved_handler op_wr; // paused write op
  101. saved_handler op_ping; // paused ping op
  102. saved_handler op_idle_ping; // paused idle ping op
  103. saved_handler op_close; // paused close op
  104. saved_handler op_r_rd; // paused read op (async read)
  105. saved_handler op_r_close; // paused close op (async read)
  106. bool idle_pinging = false;
  107. bool secure_prng_ = true;
  108. bool ec_delivered = false;
  109. bool timed_out = false;
  110. int idle_counter = 0;
  111. detail::decorator decorator_opt; // Decorator for HTTP messages
  112. timeout timeout_opt; // Timeout/idle settings
  113. template<class... Args>
  114. impl_type(Args&&... args)
  115. : boost::empty_value<NextLayer>(
  116. boost::empty_init_t{},
  117. std::forward<Args>(args)...)
  118. , detail::service::impl_type(
  119. this->get_context(
  120. this->boost::empty_value<NextLayer>::get().get_executor()))
  121. , timer(this->boost::empty_value<NextLayer>::get().get_executor())
  122. {
  123. timeout_opt.handshake_timeout = none();
  124. timeout_opt.idle_timeout = none();
  125. timeout_opt.keep_alive_pings = false;
  126. }
  127. void
  128. shutdown() override
  129. {
  130. op_rd.reset();
  131. op_wr.reset();
  132. op_ping.reset();
  133. op_idle_ping.reset();
  134. op_close.reset();
  135. op_r_rd.reset();
  136. op_r_close.reset();
  137. }
  138. void
  139. open(role_type role_)
  140. {
  141. // VFALCO TODO analyze and remove dupe code in reset()
  142. timer.expires_at(never());
  143. timed_out = false;
  144. cr.code = close_code::none;
  145. role = role_;
  146. status_ = status::open;
  147. rd_remain = 0;
  148. rd_cont = false;
  149. rd_done = true;
  150. // Can't clear this because accept uses it
  151. //rd_buf.reset();
  152. rd_fh.fin = false;
  153. rd_close = false;
  154. wr_close = false;
  155. // These should not be necessary, because all completion
  156. // handlers must be allowed to execute otherwise the
  157. // stream exhibits undefined behavior.
  158. wr_block.reset();
  159. rd_block.reset();
  160. wr_cont = false;
  161. wr_buf_size = 0;
  162. this->open_pmd(role);
  163. }
  164. void
  165. close()
  166. {
  167. timer.cancel();
  168. wr_buf.reset();
  169. this->close_pmd();
  170. }
  171. void
  172. reset()
  173. {
  174. BOOST_ASSERT(status_ != status::open);
  175. timer.expires_at(never());
  176. cr.code = close_code::none;
  177. rd_remain = 0;
  178. rd_cont = false;
  179. rd_done = true;
  180. rd_buf.consume(rd_buf.size());
  181. rd_fh.fin = false;
  182. rd_close = false;
  183. wr_close = false;
  184. wr_cont = false;
  185. // These should not be necessary, because all completion
  186. // handlers must be allowed to execute otherwise the
  187. // stream exhibits undefined behavior.
  188. wr_block.reset();
  189. rd_block.reset();
  190. // VFALCO Is this needed?
  191. timer.cancel();
  192. }
  193. void
  194. time_out()
  195. {
  196. timed_out = true;
  197. change_status(status::closed);
  198. close_socket(get_lowest_layer(stream()));
  199. }
  200. // Called just before sending
  201. // the first frame of each message
  202. void
  203. begin_msg(std::size_t n_bytes)
  204. {
  205. wr_frag = wr_frag_opt;
  206. wr_compress =
  207. this->pmd_enabled() &&
  208. wr_compress_opt &&
  209. this->should_compress(n_bytes);
  210. // Maintain the write buffer
  211. if( this->pmd_enabled() ||
  212. role == role_type::client)
  213. {
  214. if(! wr_buf ||
  215. wr_buf_size != wr_buf_opt)
  216. {
  217. wr_buf_size = wr_buf_opt;
  218. wr_buf = boost::make_unique_noinit<
  219. std::uint8_t[]>(wr_buf_size);
  220. }
  221. }
  222. else
  223. {
  224. wr_buf_size = wr_buf_opt;
  225. wr_buf.reset();
  226. }
  227. //
  228. }
  229. //--------------------------------------------------------------------------
  230. template<class Decorator>
  231. request_type
  232. build_request(
  233. detail::sec_ws_key_type& key,
  234. string_view host, string_view target,
  235. Decorator const& decorator);
  236. void
  237. on_response(
  238. response_type const& res,
  239. detail::sec_ws_key_type const& key,
  240. error_code& ec);
  241. template<class Body, class Allocator, class Decorator>
  242. response_type
  243. build_response(
  244. http::request<Body,
  245. http::basic_fields<Allocator>> const& req,
  246. Decorator const& decorator,
  247. error_code& result);
  248. // Attempt to read a complete frame header.
  249. // Returns `false` if more bytes are needed
  250. template<class DynamicBuffer>
  251. bool
  252. parse_fh(detail::frame_header& fh,
  253. DynamicBuffer& b, error_code& ec);
  254. std::uint32_t
  255. create_mask()
  256. {
  257. auto g = detail::make_prng(secure_prng_);
  258. for(;;)
  259. if(auto key = g())
  260. return key;
  261. }
  262. template<class DynamicBuffer>
  263. std::size_t
  264. read_size_hint_db(DynamicBuffer& buffer) const
  265. {
  266. auto const initial_size = (std::min)(
  267. +tcp_frame_size,
  268. buffer.max_size() - buffer.size());
  269. if(initial_size == 0)
  270. return 1; // buffer is full
  271. return this->read_size_hint_pmd(
  272. initial_size, rd_done, rd_msg_max, rd_remain, rd_fh);
  273. }
  274. template<class DynamicBuffer>
  275. void
  276. write_ping(DynamicBuffer& db,
  277. detail::opcode code, ping_data const& data);
  278. template<class DynamicBuffer>
  279. void
  280. write_close(DynamicBuffer& db, close_reason const& cr);
  281. //--------------------------------------------------------------------------
  282. void
  283. set_option(timeout const& opt)
  284. {
  285. if( opt.handshake_timeout == none() &&
  286. opt.idle_timeout == none())
  287. {
  288. // turn timer off
  289. timer.cancel();
  290. timer.expires_at(never());
  291. }
  292. timeout_opt = opt;
  293. }
  294. // Determine if an operation should stop and
  295. // deliver an error code to the completion handler.
  296. //
  297. // This function must be called at the beginning
  298. // of every composed operation, and every time a
  299. // composed operation receives an intermediate
  300. // completion.
  301. //
  302. bool
  303. check_stop_now(error_code& ec)
  304. {
  305. // Deliver the timeout to the first caller
  306. if(timed_out)
  307. {
  308. timed_out = false;
  309. BOOST_BEAST_ASSIGN_EC(ec, beast::error::timeout);
  310. return true;
  311. }
  312. // If the stream is closed then abort
  313. if( status_ == status::closed ||
  314. status_ == status::failed)
  315. {
  316. //BOOST_ASSERT(ec_delivered);
  317. BOOST_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  318. return true;
  319. }
  320. // If no error then keep going
  321. if(! ec)
  322. return false;
  323. // Is this the first error seen?
  324. if(ec_delivered)
  325. {
  326. // No, so abort
  327. BOOST_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  328. return true;
  329. }
  330. // Deliver the error to the completion handler
  331. ec_delivered = true;
  332. if(status_ != status::closed)
  333. status_ = status::failed;
  334. return true;
  335. }
  336. // Change the status of the stream
  337. void
  338. change_status(status new_status)
  339. {
  340. switch(new_status)
  341. {
  342. case status::handshake:
  343. break;
  344. case status::open:
  345. break;
  346. case status::closing:
  347. //BOOST_ASSERT(status_ == status::open);
  348. break;
  349. case status::failed:
  350. case status::closed:
  351. // this->close(); // Is this right?
  352. break;
  353. default:
  354. break;
  355. }
  356. status_ = new_status;
  357. }
  358. // Called to disarm the idle timeout counter
  359. void
  360. reset_idle()
  361. {
  362. idle_counter = 0;
  363. }
  364. // Maintain the expiration timer
  365. template<class Executor>
  366. void
  367. update_timer(Executor const& ex)
  368. {
  369. switch(status_)
  370. {
  371. case status::handshake:
  372. BOOST_ASSERT(idle_counter == 0);
  373. if(! is_timer_set() &&
  374. timeout_opt.handshake_timeout != none())
  375. {
  376. timer.expires_after(
  377. timeout_opt.handshake_timeout);
  378. BOOST_ASIO_HANDLER_LOCATION((
  379. __FILE__, __LINE__,
  380. "websocket::check_stop_now"
  381. ));
  382. timer.async_wait(
  383. timeout_handler<Executor>(
  384. ex, this->weak_from_this()));
  385. }
  386. break;
  387. case status::open:
  388. if(timeout_opt.idle_timeout != none())
  389. {
  390. idle_counter = 0;
  391. if(timeout_opt.keep_alive_pings)
  392. timer.expires_after(
  393. timeout_opt.idle_timeout / 2);
  394. else
  395. timer.expires_after(
  396. timeout_opt.idle_timeout);
  397. BOOST_ASIO_HANDLER_LOCATION((
  398. __FILE__, __LINE__,
  399. "websocket::check_stop_now"
  400. ));
  401. timer.async_wait(
  402. timeout_handler<Executor>(
  403. ex, this->weak_from_this()));
  404. }
  405. else
  406. {
  407. timer.cancel();
  408. timer.expires_at(never());
  409. }
  410. break;
  411. case status::closing:
  412. if(timeout_opt.handshake_timeout != none())
  413. {
  414. idle_counter = 0;
  415. timer.expires_after(
  416. timeout_opt.handshake_timeout);
  417. BOOST_ASIO_HANDLER_LOCATION((
  418. __FILE__, __LINE__,
  419. "websocket::check_stop_now"
  420. ));
  421. timer.async_wait(
  422. timeout_handler<Executor>(
  423. ex, this->weak_from_this()));
  424. }
  425. else
  426. {
  427. // VFALCO This assert goes off when there's also
  428. // a pending read with the timer set. The bigger
  429. // fix is to give close its own timeout, instead
  430. // of using the handshake timeout.
  431. // BOOST_ASSERT(! is_timer_set());
  432. }
  433. break;
  434. case status::failed:
  435. case status::closed:
  436. // this->close(); // Is this right?
  437. timer.cancel();
  438. timer.expires_at(never());
  439. break;
  440. }
  441. }
  442. private:
  443. template<class Executor>
  444. static net::execution_context&
  445. get_context(Executor const& ex,
  446. typename std::enable_if< net::execution::is_executor<Executor>::value >::type* = 0)
  447. {
  448. return net::query(ex, net::execution::context);
  449. }
  450. template<class Executor>
  451. static net::execution_context&
  452. get_context(Executor const& ex,
  453. typename std::enable_if< !net::execution::is_executor<Executor>::value >::type* = 0)
  454. {
  455. return ex.context();
  456. }
  457. bool
  458. is_timer_set() const
  459. {
  460. return timer.expiry() != never();
  461. }
  462. template<class Executor>
  463. class timeout_handler
  464. : boost::empty_value<Executor>
  465. {
  466. boost::weak_ptr<impl_type> wp_;
  467. public:
  468. timeout_handler(
  469. Executor const& ex,
  470. boost::weak_ptr<impl_type>&& wp)
  471. : boost::empty_value<Executor>(
  472. boost::empty_init_t{}, ex)
  473. , wp_(std::move(wp))
  474. {
  475. }
  476. using executor_type = Executor;
  477. executor_type
  478. get_executor() const noexcept
  479. {
  480. return this->get();
  481. }
  482. void
  483. operator()(error_code ec)
  484. {
  485. // timer canceled?
  486. if(ec == net::error::operation_aborted)
  487. return;
  488. BOOST_ASSERT(! ec);
  489. // stream destroyed?
  490. auto sp = wp_.lock();
  491. if(! sp)
  492. return;
  493. auto& impl = *sp;
  494. switch(impl.status_)
  495. {
  496. case status::handshake:
  497. impl.time_out();
  498. return;
  499. case status::open:
  500. // timeout was disabled
  501. if(impl.timeout_opt.idle_timeout == none())
  502. return;
  503. if( impl.timeout_opt.keep_alive_pings &&
  504. impl.idle_counter < 1)
  505. {
  506. {
  507. BOOST_ASIO_HANDLER_LOCATION((
  508. __FILE__, __LINE__,
  509. "websocket::timeout_handler"
  510. ));
  511. idle_ping_op<Executor>(sp, get_executor());
  512. }
  513. ++impl.idle_counter;
  514. impl.timer.expires_after(
  515. impl.timeout_opt.idle_timeout / 2);
  516. {
  517. BOOST_ASIO_HANDLER_LOCATION((
  518. __FILE__, __LINE__,
  519. "websocket::timeout_handler"
  520. ));
  521. impl.timer.async_wait(std::move(*this));
  522. }
  523. return;
  524. }
  525. impl.time_out();
  526. return;
  527. case status::closing:
  528. impl.time_out();
  529. return;
  530. case status::closed:
  531. case status::failed:
  532. // nothing to do?
  533. return;
  534. }
  535. }
  536. };
  537. };
  538. //--------------------------------------------------------------------------
  539. //
  540. // client
  541. //
  542. //--------------------------------------------------------------------------
  543. template<class NextLayer, bool deflateSupported>
  544. template<class Decorator>
  545. request_type
  546. stream<NextLayer, deflateSupported>::impl_type::
  547. build_request(
  548. detail::sec_ws_key_type& key,
  549. string_view host, string_view target,
  550. Decorator const& decorator)
  551. {
  552. request_type req;
  553. req.target(target);
  554. req.version(11);
  555. req.method(http::verb::get);
  556. req.set(http::field::host, host);
  557. req.set(http::field::upgrade, "websocket");
  558. req.set(http::field::connection, "Upgrade");
  559. detail::make_sec_ws_key(key);
  560. req.set(http::field::sec_websocket_key, to_string_view(key));
  561. req.set(http::field::sec_websocket_version, "13");
  562. this->build_request_pmd(req);
  563. decorator_opt(req);
  564. decorator(req);
  565. return req;
  566. }
  567. // Called when the WebSocket Upgrade response is received
  568. template<class NextLayer, bool deflateSupported>
  569. void
  570. stream<NextLayer, deflateSupported>::impl_type::
  571. on_response(
  572. response_type const& res,
  573. detail::sec_ws_key_type const& key,
  574. error_code& ec)
  575. {
  576. auto const err =
  577. [&](error e)
  578. {
  579. BOOST_BEAST_ASSIGN_EC(ec, e);
  580. };
  581. if(res.result() != http::status::switching_protocols)
  582. return err(error::upgrade_declined);
  583. if(res.version() != 11)
  584. return err(error::bad_http_version);
  585. {
  586. auto const it = res.find(http::field::connection);
  587. if(it == res.end())
  588. return err(error::no_connection);
  589. if(! http::token_list{it->value()}.exists("upgrade"))
  590. return err(error::no_connection_upgrade);
  591. }
  592. {
  593. auto const it = res.find(http::field::upgrade);
  594. if(it == res.end())
  595. return err(error::no_upgrade);
  596. if(! http::token_list{it->value()}.exists("websocket"))
  597. return err(error::no_upgrade_websocket);
  598. }
  599. {
  600. auto const it = res.find(
  601. http::field::sec_websocket_accept);
  602. if(it == res.end())
  603. return err(error::no_sec_accept);
  604. detail::sec_ws_accept_type acc;
  605. detail::make_sec_ws_accept(acc, to_string_view(key));
  606. if (to_string_view(acc).compare(it->value()) != 0)
  607. return err(error::bad_sec_accept);
  608. }
  609. ec = {};
  610. this->on_response_pmd(res);
  611. this->open(role_type::client);
  612. }
  613. //------------------------------------------------------------------------------
  614. // Attempt to read a complete frame header.
  615. // Returns `false` if more bytes are needed
  616. template<class NextLayer, bool deflateSupported>
  617. template<class DynamicBuffer>
  618. bool
  619. stream<NextLayer, deflateSupported>::impl_type::
  620. parse_fh(
  621. detail::frame_header& fh,
  622. DynamicBuffer& b,
  623. error_code& ec)
  624. {
  625. if(buffer_bytes(b.data()) < 2)
  626. {
  627. // need more bytes
  628. ec = {};
  629. return false;
  630. }
  631. buffers_suffix<typename
  632. DynamicBuffer::const_buffers_type> cb{
  633. b.data()};
  634. std::size_t need;
  635. {
  636. std::uint8_t tmp[2];
  637. cb.consume(net::buffer_copy(
  638. net::buffer(tmp), cb));
  639. fh.len = tmp[1] & 0x7f;
  640. switch(fh.len)
  641. {
  642. case 126: need = 2; break;
  643. case 127: need = 8; break;
  644. default:
  645. need = 0;
  646. }
  647. fh.mask = (tmp[1] & 0x80) != 0;
  648. if(fh.mask)
  649. need += 4;
  650. if(buffer_bytes(cb) < need)
  651. {
  652. // need more bytes
  653. ec = {};
  654. return false;
  655. }
  656. fh.op = static_cast<
  657. detail::opcode>(tmp[0] & 0x0f);
  658. fh.fin = (tmp[0] & 0x80) != 0;
  659. fh.rsv1 = (tmp[0] & 0x40) != 0;
  660. fh.rsv2 = (tmp[0] & 0x20) != 0;
  661. fh.rsv3 = (tmp[0] & 0x10) != 0;
  662. }
  663. switch(fh.op)
  664. {
  665. case detail::opcode::binary:
  666. case detail::opcode::text:
  667. if(rd_cont)
  668. {
  669. // new data frame when continuation expected
  670. BOOST_BEAST_ASSIGN_EC(ec, error::bad_data_frame);
  671. return false;
  672. }
  673. if(fh.rsv2 || fh.rsv3 ||
  674. ! this->rd_deflated(fh.rsv1))
  675. {
  676. // reserved bits not cleared
  677. BOOST_BEAST_ASSIGN_EC(ec, error::bad_reserved_bits);
  678. return false;
  679. }
  680. break;
  681. case detail::opcode::cont:
  682. if(! rd_cont)
  683. {
  684. // continuation without an active message
  685. BOOST_BEAST_ASSIGN_EC(ec, error::bad_continuation);
  686. return false;
  687. }
  688. if(fh.rsv1 || fh.rsv2 || fh.rsv3)
  689. {
  690. // reserved bits not cleared
  691. BOOST_BEAST_ASSIGN_EC(ec, error::bad_reserved_bits);
  692. return false;
  693. }
  694. break;
  695. default:
  696. if(detail::is_reserved(fh.op))
  697. {
  698. // reserved opcode
  699. BOOST_BEAST_ASSIGN_EC(ec, error::bad_opcode);
  700. return false;
  701. }
  702. if(! fh.fin)
  703. {
  704. // fragmented control message
  705. BOOST_BEAST_ASSIGN_EC(ec, error::bad_control_fragment);
  706. return false;
  707. }
  708. if(fh.len > 125)
  709. {
  710. // invalid length for control message
  711. BOOST_BEAST_ASSIGN_EC(ec, error::bad_control_size);
  712. return false;
  713. }
  714. if(fh.rsv1 || fh.rsv2 || fh.rsv3)
  715. {
  716. // reserved bits not cleared
  717. BOOST_BEAST_ASSIGN_EC(ec, error::bad_reserved_bits);
  718. return false;
  719. }
  720. break;
  721. }
  722. if(role == role_type::server && ! fh.mask)
  723. {
  724. // unmasked frame from client
  725. BOOST_BEAST_ASSIGN_EC(ec, error::bad_unmasked_frame);
  726. return false;
  727. }
  728. if(role == role_type::client && fh.mask)
  729. {
  730. // masked frame from server
  731. BOOST_BEAST_ASSIGN_EC(ec, error::bad_masked_frame);
  732. return false;
  733. }
  734. if(detail::is_control(fh.op) &&
  735. buffer_bytes(cb) < need + fh.len)
  736. {
  737. // Make the entire control frame payload
  738. // get read in before we return `true`
  739. return false;
  740. }
  741. switch(fh.len)
  742. {
  743. case 126:
  744. {
  745. std::uint16_t len_be;
  746. BOOST_ASSERT(buffer_bytes(cb) >= sizeof(len_be));
  747. cb.consume(net::buffer_copy(
  748. net::mutable_buffer(&len_be, sizeof(len_be)), cb));
  749. fh.len = endian::big_to_native(len_be);
  750. if(fh.len < 126)
  751. {
  752. // length not canonical
  753. BOOST_BEAST_ASSIGN_EC(ec, error::bad_size);
  754. return false;
  755. }
  756. break;
  757. }
  758. case 127:
  759. {
  760. std::uint64_t len_be;
  761. BOOST_ASSERT(buffer_bytes(cb) >= sizeof(len_be));
  762. cb.consume(net::buffer_copy(
  763. net::mutable_buffer(&len_be, sizeof(len_be)), cb));
  764. fh.len = endian::big_to_native(len_be);
  765. if(fh.len < 65536)
  766. {
  767. // length not canonical
  768. BOOST_BEAST_ASSIGN_EC(ec, error::bad_size);
  769. return false;
  770. }
  771. break;
  772. }
  773. }
  774. if(fh.mask)
  775. {
  776. std::uint32_t key_le;
  777. BOOST_ASSERT(buffer_bytes(cb) >= sizeof(key_le));
  778. cb.consume(net::buffer_copy(
  779. net::mutable_buffer(&key_le, sizeof(key_le)), cb));
  780. fh.key = endian::little_to_native(key_le);
  781. detail::prepare_key(rd_key, fh.key);
  782. }
  783. else
  784. {
  785. // initialize this otherwise operator== breaks
  786. fh.key = 0;
  787. }
  788. if(! detail::is_control(fh.op))
  789. {
  790. if(fh.op != detail::opcode::cont)
  791. {
  792. rd_size = 0;
  793. rd_op = fh.op;
  794. }
  795. else
  796. {
  797. if(rd_size > (std::numeric_limits<
  798. std::uint64_t>::max)() - fh.len)
  799. {
  800. // message size exceeds configured limit
  801. BOOST_BEAST_ASSIGN_EC(ec, error::message_too_big);
  802. return false;
  803. }
  804. }
  805. // The final size of a deflated frame is unknown. In certain cases,
  806. // post-inflation, it might shrink and become <= rd_msg_max.
  807. // Therefore, we will verify the size during the inflation process.
  808. if(! this->rd_deflated())
  809. {
  810. if(rd_msg_max && beast::detail::sum_exceeds(
  811. rd_size, fh.len, rd_msg_max))
  812. {
  813. // message size exceeds configured limit
  814. BOOST_BEAST_ASSIGN_EC(ec, error::message_too_big);
  815. return false;
  816. }
  817. }
  818. rd_cont = ! fh.fin;
  819. rd_remain = fh.len;
  820. }
  821. b.consume(b.size() - buffer_bytes(cb));
  822. ec = {};
  823. return true;
  824. }
  825. template<class NextLayer, bool deflateSupported>
  826. template<class DynamicBuffer>
  827. void
  828. stream<NextLayer, deflateSupported>::impl_type::
  829. write_ping(DynamicBuffer& db,
  830. detail::opcode code, ping_data const& data)
  831. {
  832. detail::frame_header fh;
  833. fh.op = code;
  834. fh.fin = true;
  835. fh.rsv1 = false;
  836. fh.rsv2 = false;
  837. fh.rsv3 = false;
  838. fh.len = data.size();
  839. fh.mask = role == role_type::client;
  840. if(fh.mask)
  841. fh.key = create_mask();
  842. detail::write(db, fh);
  843. if(data.empty())
  844. return;
  845. detail::prepared_key key;
  846. if(fh.mask)
  847. detail::prepare_key(key, fh.key);
  848. auto mb = db.prepare(data.size());
  849. net::buffer_copy(mb,
  850. net::const_buffer(
  851. data.data(), data.size()));
  852. if(fh.mask)
  853. detail::mask_inplace(mb, key);
  854. db.commit(data.size());
  855. }
  856. template<class NextLayer, bool deflateSupported>
  857. template<class DynamicBuffer>
  858. void
  859. stream<NextLayer, deflateSupported>::impl_type::
  860. write_close(DynamicBuffer& db, close_reason const& cr)
  861. {
  862. using namespace boost::endian;
  863. detail::frame_header fh;
  864. fh.op = detail::opcode::close;
  865. fh.fin = true;
  866. fh.rsv1 = false;
  867. fh.rsv2 = false;
  868. fh.rsv3 = false;
  869. fh.len = cr.code == close_code::none ?
  870. 0 : 2 + cr.reason.size();
  871. if(role == role_type::client)
  872. {
  873. fh.mask = true;
  874. fh.key = create_mask();
  875. }
  876. else
  877. {
  878. fh.mask = false;
  879. }
  880. detail::write(db, fh);
  881. if(cr.code != close_code::none)
  882. {
  883. detail::prepared_key key;
  884. if(fh.mask)
  885. detail::prepare_key(key, fh.key);
  886. {
  887. auto code_be = endian::native_to_big<std::uint16_t>(cr.code);
  888. auto mb = db.prepare(2);
  889. net::buffer_copy(mb,
  890. net::const_buffer(&code_be, sizeof(code_be)));
  891. if(fh.mask)
  892. detail::mask_inplace(mb, key);
  893. db.commit(2);
  894. }
  895. if(! cr.reason.empty())
  896. {
  897. auto mb = db.prepare(cr.reason.size());
  898. net::buffer_copy(mb,
  899. net::const_buffer(
  900. cr.reason.data(), cr.reason.size()));
  901. if(fh.mask)
  902. detail::mask_inplace(mb, key);
  903. db.commit(cr.reason.size());
  904. }
  905. }
  906. }
  907. } // websocket
  908. } // beast
  909. } // boost
  910. #endif