stream_impl.hpp 29 KB

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