stream_impl.hpp 28 KB

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