stream_impl.hpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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/beast/version.hpp>
  32. #include <boost/asio/steady_timer.hpp>
  33. #include <boost/core/empty_value.hpp>
  34. #include <boost/enable_shared_from_this.hpp>
  35. #include <boost/shared_ptr.hpp>
  36. #include <boost/optional.hpp>
  37. namespace boost {
  38. namespace beast {
  39. namespace websocket {
  40. template<
  41. class NextLayer, bool deflateSupported>
  42. struct stream<NextLayer, deflateSupported>::impl_type
  43. : boost::empty_value<NextLayer>
  44. , detail::service::impl_type
  45. , detail::impl_base<deflateSupported>
  46. {
  47. NextLayer& stream() noexcept
  48. {
  49. return this->boost::empty_value<
  50. NextLayer>::get();
  51. }
  52. boost::weak_ptr<impl_type>
  53. weak_from_this()
  54. {
  55. return boost::static_pointer_cast<
  56. impl_type>(this->detail::service::
  57. impl_type::shared_from_this());
  58. }
  59. boost::shared_ptr<impl_type>
  60. shared_this()
  61. {
  62. return boost::static_pointer_cast<
  63. impl_type>(this->detail::service::
  64. impl_type::shared_from_this());
  65. }
  66. net::steady_timer timer; // used for timeouts
  67. close_reason cr; // set from received close frame
  68. control_cb_type ctrl_cb; // control callback
  69. std::size_t rd_msg_max /* max message size */ = 16 * 1024 * 1024;
  70. std::uint64_t rd_size /* total size of current message so far */ = 0;
  71. std::uint64_t rd_remain /* message frame bytes left in current frame */ = 0;
  72. detail::frame_header rd_fh; // current frame header
  73. detail::prepared_key rd_key; // current stateful mask key
  74. detail::frame_buffer rd_fb; // to write control frames (during reads)
  75. detail::utf8_checker rd_utf8; // to validate utf8
  76. static_buffer<
  77. +tcp_frame_size> rd_buf; // buffer for reads
  78. detail::opcode rd_op /* current message binary or text */ = detail::opcode::text;
  79. bool rd_cont /* `true` if the next frame is a continuation */ = false;
  80. bool rd_done /* set when a message is done */ = true;
  81. bool rd_close /* did we read a close frame? */ = false;
  82. detail::soft_mutex rd_block; // op currently reading
  83. role_type role /* server or client */ = role_type::client;
  84. status status_ /* state of the object */ = status::closed;
  85. detail::soft_mutex wr_block; // op currently writing
  86. bool wr_close /* did we write a close frame? */ = false;
  87. bool wr_cont /* next write is a continuation */ = false;
  88. bool wr_frag /* autofrag the current message */ = false;
  89. bool wr_frag_opt /* autofrag option setting */ = true;
  90. bool wr_compress; /* compress current message */
  91. bool wr_compress_opt /* compress message setting */ = true;
  92. detail::opcode wr_opcode /* message type */ = detail::opcode::text;
  93. std::unique_ptr<
  94. std::uint8_t[]> wr_buf; // write buffer
  95. std::size_t wr_buf_size /* write buffer size (current message) */ = 0;
  96. std::size_t wr_buf_opt /* write buffer size option setting */ = 4096;
  97. detail::fh_buffer wr_fb; // header buffer used for writes
  98. saved_handler op_rd; // paused read op
  99. saved_handler op_wr; // paused write op
  100. saved_handler op_ping; // paused ping op
  101. saved_handler op_idle_ping; // paused idle ping op
  102. saved_handler op_close; // paused close op
  103. saved_handler op_r_rd; // paused read op (async read)
  104. saved_handler op_r_close; // paused close op (async read)
  105. bool idle_pinging = false;
  106. bool secure_prng_ = true;
  107. bool ec_delivered = false;
  108. bool timed_out = false;
  109. int idle_counter = 0;
  110. detail::decorator decorator_opt; // Decorator for HTTP messages
  111. timeout timeout_opt; // Timeout/idle settings
  112. template<class... Args>
  113. impl_type(Args&&... args)
  114. : boost::empty_value<NextLayer>(
  115. boost::empty_init_t{},
  116. std::forward<Args>(args)...)
  117. , detail::service::impl_type(
  118. this->boost::empty_value<NextLayer>::get().get_executor().context())
  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. timer.async_wait(
  375. timeout_handler<Executor>(
  376. ex, this->weak_from_this()));
  377. }
  378. break;
  379. case status::open:
  380. if(timeout_opt.idle_timeout != none())
  381. {
  382. idle_counter = 0;
  383. if(timeout_opt.keep_alive_pings)
  384. timer.expires_after(
  385. timeout_opt.idle_timeout / 2);
  386. else
  387. timer.expires_after(
  388. timeout_opt.idle_timeout);
  389. timer.async_wait(
  390. timeout_handler<Executor>(
  391. ex, this->weak_from_this()));
  392. }
  393. else
  394. {
  395. timer.cancel();
  396. timer.expires_at(never());
  397. }
  398. break;
  399. case status::closing:
  400. if(timeout_opt.handshake_timeout != none())
  401. {
  402. idle_counter = 0;
  403. timer.expires_after(
  404. timeout_opt.handshake_timeout);
  405. timer.async_wait(
  406. timeout_handler<Executor>(
  407. ex, this->weak_from_this()));
  408. }
  409. else
  410. {
  411. // VFALCO This assert goes off when there's also
  412. // a pending read with the timer set. The bigger
  413. // fix is to give close its own timeout, instead
  414. // of using the handshake timeout.
  415. // BOOST_ASSERT(! is_timer_set());
  416. }
  417. break;
  418. case status::failed:
  419. case status::closed:
  420. // this->close(); // Is this right?
  421. timer.cancel();
  422. timer.expires_at(never());
  423. break;
  424. }
  425. }
  426. private:
  427. bool
  428. is_timer_set() const
  429. {
  430. return timer.expiry() != never();
  431. }
  432. template<class Executor>
  433. class timeout_handler
  434. : boost::empty_value<Executor>
  435. {
  436. boost::weak_ptr<impl_type> wp_;
  437. public:
  438. timeout_handler(
  439. Executor const& ex,
  440. boost::weak_ptr<impl_type>&& wp)
  441. : boost::empty_value<Executor>(
  442. boost::empty_init_t{}, ex)
  443. , wp_(std::move(wp))
  444. {
  445. }
  446. using executor_type = Executor;
  447. executor_type
  448. get_executor() const noexcept
  449. {
  450. return this->get();
  451. }
  452. void
  453. operator()(error_code ec)
  454. {
  455. // timer canceled?
  456. if(ec == net::error::operation_aborted)
  457. return;
  458. BOOST_ASSERT(! ec);
  459. // stream destroyed?
  460. auto sp = wp_.lock();
  461. if(! sp)
  462. return;
  463. auto& impl = *sp;
  464. switch(impl.status_)
  465. {
  466. case status::handshake:
  467. impl.time_out();
  468. return;
  469. case status::open:
  470. // timeout was disabled
  471. if(impl.timeout_opt.idle_timeout == none())
  472. return;
  473. if( impl.timeout_opt.keep_alive_pings &&
  474. impl.idle_counter < 1)
  475. {
  476. idle_ping_op<Executor>(sp, get_executor());
  477. ++impl.idle_counter;
  478. impl.timer.expires_after(
  479. impl.timeout_opt.idle_timeout / 2);
  480. impl.timer.async_wait(std::move(*this));
  481. return;
  482. }
  483. impl.time_out();
  484. return;
  485. case status::closing:
  486. impl.time_out();
  487. return;
  488. case status::closed:
  489. case status::failed:
  490. // nothing to do?
  491. return;
  492. }
  493. }
  494. };
  495. };
  496. //--------------------------------------------------------------------------
  497. //
  498. // client
  499. //
  500. //--------------------------------------------------------------------------
  501. template<class NextLayer, bool deflateSupported>
  502. template<class Decorator>
  503. request_type
  504. stream<NextLayer, deflateSupported>::impl_type::
  505. build_request(
  506. detail::sec_ws_key_type& key,
  507. string_view host, string_view target,
  508. Decorator const& decorator)
  509. {
  510. request_type req;
  511. req.target(target);
  512. req.version(11);
  513. req.method(http::verb::get);
  514. req.set(http::field::host, host);
  515. req.set(http::field::upgrade, "websocket");
  516. req.set(http::field::connection, "upgrade");
  517. detail::make_sec_ws_key(key);
  518. req.set(http::field::sec_websocket_key, key);
  519. req.set(http::field::sec_websocket_version, "13");
  520. this->build_request_pmd(req);
  521. decorator_opt(req);
  522. decorator(req);
  523. if(! req.count(http::field::user_agent))
  524. req.set(http::field::user_agent,
  525. BOOST_BEAST_VERSION_STRING);
  526. return req;
  527. }
  528. // Called when the WebSocket Upgrade response is received
  529. template<class NextLayer, bool deflateSupported>
  530. void
  531. stream<NextLayer, deflateSupported>::impl_type::
  532. on_response(
  533. response_type const& res,
  534. detail::sec_ws_key_type const& key,
  535. error_code& ec)
  536. {
  537. auto const err =
  538. [&](error e)
  539. {
  540. ec = e;
  541. };
  542. if(res.result() != http::status::switching_protocols)
  543. return err(error::upgrade_declined);
  544. if(res.version() != 11)
  545. return err(error::bad_http_version);
  546. {
  547. auto const it = res.find(http::field::connection);
  548. if(it == res.end())
  549. return err(error::no_connection);
  550. if(! http::token_list{it->value()}.exists("upgrade"))
  551. return err(error::no_connection_upgrade);
  552. }
  553. {
  554. auto const it = res.find(http::field::upgrade);
  555. if(it == res.end())
  556. return err(error::no_upgrade);
  557. if(! http::token_list{it->value()}.exists("websocket"))
  558. return err(error::no_upgrade_websocket);
  559. }
  560. {
  561. auto const it = res.find(
  562. http::field::sec_websocket_accept);
  563. if(it == res.end())
  564. return err(error::no_sec_accept);
  565. detail::sec_ws_accept_type acc;
  566. detail::make_sec_ws_accept(acc, key);
  567. if(acc.compare(it->value()) != 0)
  568. return err(error::bad_sec_accept);
  569. }
  570. ec = {};
  571. this->on_response_pmd(res);
  572. this->open(role_type::client);
  573. }
  574. //------------------------------------------------------------------------------
  575. // Attempt to read a complete frame header.
  576. // Returns `false` if more bytes are needed
  577. template<class NextLayer, bool deflateSupported>
  578. template<class DynamicBuffer>
  579. bool
  580. stream<NextLayer, deflateSupported>::impl_type::
  581. parse_fh(
  582. detail::frame_header& fh,
  583. DynamicBuffer& b,
  584. error_code& ec)
  585. {
  586. if(buffer_bytes(b.data()) < 2)
  587. {
  588. // need more bytes
  589. ec = {};
  590. return false;
  591. }
  592. buffers_suffix<typename
  593. DynamicBuffer::const_buffers_type> cb{
  594. b.data()};
  595. std::size_t need;
  596. {
  597. std::uint8_t tmp[2];
  598. cb.consume(net::buffer_copy(
  599. net::buffer(tmp), cb));
  600. fh.len = tmp[1] & 0x7f;
  601. switch(fh.len)
  602. {
  603. case 126: need = 2; break;
  604. case 127: need = 8; break;
  605. default:
  606. need = 0;
  607. }
  608. fh.mask = (tmp[1] & 0x80) != 0;
  609. if(fh.mask)
  610. need += 4;
  611. if(buffer_bytes(cb) < need)
  612. {
  613. // need more bytes
  614. ec = {};
  615. return false;
  616. }
  617. fh.op = static_cast<
  618. detail::opcode>(tmp[0] & 0x0f);
  619. fh.fin = (tmp[0] & 0x80) != 0;
  620. fh.rsv1 = (tmp[0] & 0x40) != 0;
  621. fh.rsv2 = (tmp[0] & 0x20) != 0;
  622. fh.rsv3 = (tmp[0] & 0x10) != 0;
  623. }
  624. switch(fh.op)
  625. {
  626. case detail::opcode::binary:
  627. case detail::opcode::text:
  628. if(rd_cont)
  629. {
  630. // new data frame when continuation expected
  631. ec = error::bad_data_frame;
  632. return false;
  633. }
  634. if(fh.rsv2 || fh.rsv3 ||
  635. ! this->rd_deflated(fh.rsv1))
  636. {
  637. // reserved bits not cleared
  638. ec = error::bad_reserved_bits;
  639. return false;
  640. }
  641. break;
  642. case detail::opcode::cont:
  643. if(! rd_cont)
  644. {
  645. // continuation without an active message
  646. ec = error::bad_continuation;
  647. return false;
  648. }
  649. if(fh.rsv1 || fh.rsv2 || fh.rsv3)
  650. {
  651. // reserved bits not cleared
  652. ec = error::bad_reserved_bits;
  653. return false;
  654. }
  655. break;
  656. default:
  657. if(detail::is_reserved(fh.op))
  658. {
  659. // reserved opcode
  660. ec = error::bad_opcode;
  661. return false;
  662. }
  663. if(! fh.fin)
  664. {
  665. // fragmented control message
  666. ec = error::bad_control_fragment;
  667. return false;
  668. }
  669. if(fh.len > 125)
  670. {
  671. // invalid length for control message
  672. ec = error::bad_control_size;
  673. return false;
  674. }
  675. if(fh.rsv1 || fh.rsv2 || fh.rsv3)
  676. {
  677. // reserved bits not cleared
  678. ec = error::bad_reserved_bits;
  679. return false;
  680. }
  681. break;
  682. }
  683. if(role == role_type::server && ! fh.mask)
  684. {
  685. // unmasked frame from client
  686. ec = error::bad_unmasked_frame;
  687. return false;
  688. }
  689. if(role == role_type::client && fh.mask)
  690. {
  691. // masked frame from server
  692. ec = error::bad_masked_frame;
  693. return false;
  694. }
  695. if(detail::is_control(fh.op) &&
  696. buffer_bytes(cb) < need + fh.len)
  697. {
  698. // Make the entire control frame payload
  699. // get read in before we return `true`
  700. return false;
  701. }
  702. switch(fh.len)
  703. {
  704. case 126:
  705. {
  706. std::uint16_t len_be;
  707. BOOST_ASSERT(buffer_bytes(cb) >= sizeof(len_be));
  708. cb.consume(net::buffer_copy(
  709. net::mutable_buffer(&len_be, sizeof(len_be)), cb));
  710. fh.len = endian::big_to_native(len_be);
  711. if(fh.len < 126)
  712. {
  713. // length not canonical
  714. ec = error::bad_size;
  715. return false;
  716. }
  717. break;
  718. }
  719. case 127:
  720. {
  721. std::uint64_t len_be;
  722. BOOST_ASSERT(buffer_bytes(cb) >= sizeof(len_be));
  723. cb.consume(net::buffer_copy(
  724. net::mutable_buffer(&len_be, sizeof(len_be)), cb));
  725. fh.len = endian::big_to_native(len_be);
  726. if(fh.len < 65536)
  727. {
  728. // length not canonical
  729. ec = error::bad_size;
  730. return false;
  731. }
  732. break;
  733. }
  734. }
  735. if(fh.mask)
  736. {
  737. std::uint32_t key_le;
  738. BOOST_ASSERT(buffer_bytes(cb) >= sizeof(key_le));
  739. cb.consume(net::buffer_copy(
  740. net::mutable_buffer(&key_le, sizeof(key_le)), cb));
  741. fh.key = endian::little_to_native(key_le);
  742. detail::prepare_key(rd_key, fh.key);
  743. }
  744. else
  745. {
  746. // initialize this otherwise operator== breaks
  747. fh.key = 0;
  748. }
  749. if(! detail::is_control(fh.op))
  750. {
  751. if(fh.op != detail::opcode::cont)
  752. {
  753. rd_size = 0;
  754. rd_op = fh.op;
  755. }
  756. else
  757. {
  758. if(rd_size > (std::numeric_limits<
  759. std::uint64_t>::max)() - fh.len)
  760. {
  761. // message size exceeds configured limit
  762. ec = error::message_too_big;
  763. return false;
  764. }
  765. }
  766. if(! this->rd_deflated())
  767. {
  768. if(rd_msg_max && beast::detail::sum_exceeds(
  769. rd_size, fh.len, rd_msg_max))
  770. {
  771. // message size exceeds configured limit
  772. ec = error::message_too_big;
  773. return false;
  774. }
  775. }
  776. rd_cont = ! fh.fin;
  777. rd_remain = fh.len;
  778. }
  779. b.consume(b.size() - buffer_bytes(cb));
  780. ec = {};
  781. return true;
  782. }
  783. template<class NextLayer, bool deflateSupported>
  784. template<class DynamicBuffer>
  785. void
  786. stream<NextLayer, deflateSupported>::impl_type::
  787. write_ping(DynamicBuffer& db,
  788. detail::opcode code, ping_data const& data)
  789. {
  790. detail::frame_header fh;
  791. fh.op = code;
  792. fh.fin = true;
  793. fh.rsv1 = false;
  794. fh.rsv2 = false;
  795. fh.rsv3 = false;
  796. fh.len = data.size();
  797. fh.mask = role == role_type::client;
  798. if(fh.mask)
  799. fh.key = create_mask();
  800. detail::write(db, fh);
  801. if(data.empty())
  802. return;
  803. detail::prepared_key key;
  804. if(fh.mask)
  805. detail::prepare_key(key, fh.key);
  806. auto mb = db.prepare(data.size());
  807. net::buffer_copy(mb,
  808. net::const_buffer(
  809. data.data(), data.size()));
  810. if(fh.mask)
  811. detail::mask_inplace(mb, key);
  812. db.commit(data.size());
  813. }
  814. template<class NextLayer, bool deflateSupported>
  815. template<class DynamicBuffer>
  816. void
  817. stream<NextLayer, deflateSupported>::impl_type::
  818. write_close(DynamicBuffer& db, close_reason const& cr)
  819. {
  820. using namespace boost::endian;
  821. detail::frame_header fh;
  822. fh.op = detail::opcode::close;
  823. fh.fin = true;
  824. fh.rsv1 = false;
  825. fh.rsv2 = false;
  826. fh.rsv3 = false;
  827. fh.len = cr.code == close_code::none ?
  828. 0 : 2 + cr.reason.size();
  829. if(role == role_type::client)
  830. {
  831. fh.mask = true;
  832. fh.key = create_mask();
  833. }
  834. else
  835. {
  836. fh.mask = false;
  837. }
  838. detail::write(db, fh);
  839. if(cr.code != close_code::none)
  840. {
  841. detail::prepared_key key;
  842. if(fh.mask)
  843. detail::prepare_key(key, fh.key);
  844. {
  845. auto code_be = endian::native_to_big<std::uint16_t>(cr.code);
  846. auto mb = db.prepare(2);
  847. net::buffer_copy(mb,
  848. net::const_buffer(&code_be, sizeof(code_be)));
  849. if(fh.mask)
  850. detail::mask_inplace(mb, key);
  851. db.commit(2);
  852. }
  853. if(! cr.reason.empty())
  854. {
  855. auto mb = db.prepare(cr.reason.size());
  856. net::buffer_copy(mb,
  857. net::const_buffer(
  858. cr.reason.data(), cr.reason.size()));
  859. if(fh.mask)
  860. detail::mask_inplace(mb, key);
  861. db.commit(cr.reason.size());
  862. }
  863. }
  864. }
  865. } // websocket
  866. } // beast
  867. } // boost
  868. #endif