read.hpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  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_READ_HPP
  10. #define BHO_BEAST_WEBSOCKET_IMPL_READ_HPP
  11. #include <asio2/bho/beast/core/buffer_traits.hpp>
  12. #include <asio2/bho/beast/websocket/teardown.hpp>
  13. #include <asio2/bho/beast/websocket/detail/mask.hpp>
  14. #include <asio2/bho/beast/websocket/impl/stream_impl.hpp>
  15. #include <asio2/bho/beast/core/async_base.hpp>
  16. #include <asio2/bho/beast/core/bind_handler.hpp>
  17. #include <asio2/bho/beast/core/buffers_prefix.hpp>
  18. #include <asio2/bho/beast/core/buffers_suffix.hpp>
  19. #include <asio2/bho/beast/core/flat_static_buffer.hpp>
  20. #include <asio2/bho/beast/core/read_size.hpp>
  21. #include <asio2/bho/beast/core/stream_traits.hpp>
  22. #include <asio2/bho/beast/core/detail/bind_continuation.hpp>
  23. #include <asio2/bho/beast/core/detail/buffer.hpp>
  24. #include <asio2/bho/beast/core/detail/clamp.hpp>
  25. #include <asio2/bho/beast/core/detail/config.hpp>
  26. #include <asio/coroutine.hpp>
  27. #include <asio2/bho/assert.hpp>
  28. #include <asio2/bho/config.hpp>
  29. #include <optional>
  30. #include <asio2/bho/throw_exception.hpp>
  31. #include <algorithm>
  32. #include <limits>
  33. #include <memory>
  34. namespace bho {
  35. namespace beast {
  36. namespace websocket {
  37. /* Read some message data into a buffer sequence.
  38. Also reads and handles control frames.
  39. */
  40. template<class NextLayer, bool deflateSupported>
  41. template<class Handler, class MutableBufferSequence>
  42. class stream<NextLayer, deflateSupported>::read_some_op
  43. : public beast::async_base<
  44. Handler, beast::executor_type<stream>>
  45. , public asio::coroutine
  46. {
  47. std::weak_ptr<impl_type> wp_;
  48. MutableBufferSequence bs_;
  49. buffers_suffix<MutableBufferSequence> cb_;
  50. std::size_t bytes_written_ = 0;
  51. error_code result_;
  52. close_code code_;
  53. bool did_read_ = false;
  54. public:
  55. static constexpr int id = 1; // for soft_mutex
  56. template<class Handler_>
  57. read_some_op(
  58. Handler_&& h,
  59. std::shared_ptr<impl_type> const& sp,
  60. MutableBufferSequence const& bs)
  61. : async_base<
  62. Handler, beast::executor_type<stream>>(
  63. std::forward<Handler_>(h),
  64. sp->stream().get_executor())
  65. , wp_(sp)
  66. , bs_(bs)
  67. , cb_(bs)
  68. , code_(close_code::none)
  69. {
  70. (*this)({}, 0, false);
  71. }
  72. void operator()(
  73. error_code ec = {},
  74. std::size_t bytes_transferred = 0,
  75. bool cont = true)
  76. {
  77. using beast::detail::clamp;
  78. auto sp = wp_.lock();
  79. if(! sp)
  80. {
  81. BHO_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  82. bytes_written_ = 0;
  83. return this->complete(cont, ec, bytes_written_);
  84. }
  85. auto& impl = *sp;
  86. ASIO_CORO_REENTER(*this)
  87. {
  88. impl.update_timer(this->get_executor());
  89. acquire_read_lock:
  90. // Acquire the read lock
  91. if(! impl.rd_block.try_lock(this))
  92. {
  93. do_suspend:
  94. ASIO_CORO_YIELD
  95. {
  96. ASIO_HANDLER_LOCATION((
  97. __FILE__, __LINE__,
  98. "websocket::async_read_some"));
  99. this->set_allowed_cancellation(net::cancellation_type::all);
  100. impl.op_r_rd.emplace(std::move(*this), net::cancellation_type::all);
  101. }
  102. if (ec)
  103. return this->complete(cont, ec, bytes_written_);
  104. this->set_allowed_cancellation(net::cancellation_type::terminal);
  105. impl.rd_block.lock(this);
  106. ASIO_CORO_YIELD
  107. {
  108. ASIO_HANDLER_LOCATION((
  109. __FILE__, __LINE__,
  110. "websocket::async_read_some"));
  111. const auto ex = this->get_immediate_executor();
  112. net::dispatch(ex, std::move(*this));
  113. }
  114. BHO_ASSERT(impl.rd_block.is_locked(this));
  115. BHO_ASSERT(!ec);
  116. if(impl.check_stop_now(ec))
  117. {
  118. // Issue 2264 - There is no guarantee that the next
  119. // error will be operation_aborted.
  120. // The error could be a result of the peer resetting the
  121. // connection
  122. // BHO_ASSERT(ec == net::error::operation_aborted);
  123. goto upcall;
  124. }
  125. // VFALCO Should never get here
  126. // The only way to get read blocked is if
  127. // a `close_op` wrote a close frame
  128. BHO_ASSERT(impl.wr_close);
  129. BHO_ASSERT(impl.status_ != status::open);
  130. BHO_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  131. goto upcall;
  132. }
  133. else
  134. {
  135. // Make sure the stream is not closed
  136. if( impl.status_ == status::closed ||
  137. impl.status_ == status::failed)
  138. {
  139. BHO_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  140. goto upcall;
  141. }
  142. }
  143. // if status_ == status::closing, we want to suspend
  144. // the read operation until the close completes,
  145. // then finish the read with operation_aborted.
  146. loop:
  147. BHO_ASSERT(impl.rd_block.is_locked(this));
  148. // See if we need to read a frame header. This
  149. // condition is structured to give the decompressor
  150. // a chance to emit the final empty deflate block
  151. //
  152. if(impl.rd_remain == 0 &&
  153. (! impl.rd_fh.fin || impl.rd_done))
  154. {
  155. // Read frame header
  156. while(! impl.parse_fh(
  157. impl.rd_fh, impl.rd_buf, result_))
  158. {
  159. if(result_)
  160. {
  161. // _Fail the WebSocket Connection_
  162. if(result_ == error::message_too_big)
  163. code_ = close_code::too_big;
  164. else
  165. code_ = close_code::protocol_error;
  166. goto close;
  167. }
  168. BHO_ASSERT(impl.rd_block.is_locked(this));
  169. ASIO_CORO_YIELD
  170. {
  171. ASIO_HANDLER_LOCATION((
  172. __FILE__, __LINE__,
  173. "websocket::async_read_some"));
  174. impl.stream().async_read_some(
  175. impl.rd_buf.prepare(read_size(
  176. impl.rd_buf, impl.rd_buf.max_size())),
  177. std::move(*this));
  178. }
  179. BHO_ASSERT(impl.rd_block.is_locked(this));
  180. impl.rd_buf.commit(bytes_transferred);
  181. if(impl.check_stop_now(ec))
  182. goto upcall;
  183. impl.reset_idle();
  184. // Allow a close operation
  185. // to acquire the read block
  186. impl.rd_block.unlock(this);
  187. if( impl.op_r_close.maybe_invoke())
  188. {
  189. // Suspend
  190. BHO_ASSERT(impl.rd_block.is_locked());
  191. goto do_suspend;
  192. }
  193. // Acquire read block
  194. impl.rd_block.lock(this);
  195. }
  196. // Immediately apply the mask to the portion
  197. // of the buffer holding payload data.
  198. if(impl.rd_fh.len > 0 && impl.rd_fh.mask)
  199. detail::mask_inplace(buffers_prefix(
  200. clamp(impl.rd_fh.len),
  201. impl.rd_buf.data()),
  202. impl.rd_key);
  203. if(detail::is_control(impl.rd_fh.op))
  204. {
  205. // Clear this otherwise the next
  206. // frame will be considered final.
  207. impl.rd_fh.fin = false;
  208. // Handle ping frame
  209. if(impl.rd_fh.op == detail::opcode::ping)
  210. {
  211. if(impl.ctrl_cb)
  212. {
  213. if(! cont)
  214. {
  215. ASIO_CORO_YIELD
  216. {
  217. ASIO_HANDLER_LOCATION((
  218. __FILE__, __LINE__,
  219. "websocket::async_read_some"));
  220. const auto ex = this->get_immediate_executor();
  221. net::dispatch(ex, std::move(*this));
  222. }
  223. BHO_ASSERT(cont);
  224. // VFALCO call check_stop_now() here?
  225. }
  226. }
  227. {
  228. auto const b = buffers_prefix(
  229. clamp(impl.rd_fh.len),
  230. impl.rd_buf.data());
  231. auto const len = buffer_bytes(b);
  232. BHO_ASSERT(len == impl.rd_fh.len);
  233. ping_data payload;
  234. detail::read_ping(payload, b);
  235. impl.rd_buf.consume(len);
  236. // Ignore ping when closing
  237. if(impl.status_ == status::closing)
  238. goto loop;
  239. if(impl.ctrl_cb)
  240. impl.ctrl_cb(
  241. frame_type::ping, to_string_view(payload));
  242. impl.rd_fb.clear();
  243. impl.template write_ping<
  244. flat_static_buffer_base>(impl.rd_fb,
  245. detail::opcode::pong, payload);
  246. }
  247. // Allow a close operation
  248. // to acquire the read block
  249. impl.rd_block.unlock(this);
  250. impl.op_r_close.maybe_invoke();
  251. // Acquire the write lock
  252. if(! impl.wr_block.try_lock(this))
  253. {
  254. ASIO_CORO_YIELD
  255. {
  256. ASIO_HANDLER_LOCATION((
  257. __FILE__, __LINE__,
  258. "websocket::async_read_some"));
  259. impl.op_rd.emplace(std::move(*this));
  260. }
  261. if (ec)
  262. return this->complete(cont, ec, bytes_written_);
  263. impl.wr_block.lock(this);
  264. ASIO_CORO_YIELD
  265. {
  266. ASIO_HANDLER_LOCATION((
  267. __FILE__, __LINE__,
  268. "websocket::async_read_some"));
  269. const auto ex = this->get_immediate_executor();
  270. net::dispatch(ex, std::move(*this));
  271. }
  272. BHO_ASSERT(impl.wr_block.is_locked(this));
  273. if(impl.check_stop_now(ec))
  274. goto upcall;
  275. }
  276. // Send pong
  277. BHO_ASSERT(impl.wr_block.is_locked(this));
  278. ASIO_CORO_YIELD
  279. {
  280. ASIO_HANDLER_LOCATION((
  281. __FILE__, __LINE__,
  282. "websocket::async_read_some"));
  283. net::async_write(
  284. impl.stream(), net::const_buffer(impl.rd_fb.data()),
  285. beast::detail::bind_continuation(std::move(*this)));
  286. }
  287. BHO_ASSERT(impl.wr_block.is_locked(this));
  288. if(impl.check_stop_now(ec))
  289. goto upcall;
  290. impl.wr_block.unlock(this);
  291. impl.op_close.maybe_invoke()
  292. || impl.op_idle_ping.maybe_invoke()
  293. || impl.op_ping.maybe_invoke()
  294. || impl.op_wr.maybe_invoke();
  295. goto acquire_read_lock;
  296. }
  297. // Handle pong frame
  298. if(impl.rd_fh.op == detail::opcode::pong)
  299. {
  300. // Ignore pong when closing
  301. if(! impl.wr_close && impl.ctrl_cb)
  302. {
  303. if(! cont)
  304. {
  305. ASIO_CORO_YIELD
  306. {
  307. ASIO_HANDLER_LOCATION((
  308. __FILE__, __LINE__,
  309. "websocket::async_read_some"));
  310. const auto ex = this->get_immediate_executor();
  311. net::dispatch(ex, std::move(*this));
  312. }
  313. BHO_ASSERT(cont);
  314. }
  315. }
  316. auto const cb = buffers_prefix(clamp(
  317. impl.rd_fh.len), impl.rd_buf.data());
  318. auto const len = buffer_bytes(cb);
  319. BHO_ASSERT(len == impl.rd_fh.len);
  320. ping_data payload;
  321. detail::read_ping(payload, cb);
  322. impl.rd_buf.consume(len);
  323. // Ignore pong when closing
  324. if(! impl.wr_close && impl.ctrl_cb)
  325. impl.ctrl_cb(frame_type::pong, to_string_view(payload));
  326. goto loop;
  327. }
  328. // Handle close frame
  329. BHO_ASSERT(impl.rd_fh.op == detail::opcode::close);
  330. {
  331. if(impl.ctrl_cb)
  332. {
  333. if(! cont)
  334. {
  335. ASIO_CORO_YIELD
  336. {
  337. ASIO_HANDLER_LOCATION((
  338. __FILE__, __LINE__,
  339. "websocket::async_read_some"));
  340. const auto ex = this->get_immediate_executor();
  341. net::dispatch(ex, std::move(*this));
  342. }
  343. BHO_ASSERT(cont);
  344. }
  345. }
  346. auto const cb = buffers_prefix(clamp(
  347. impl.rd_fh.len), impl.rd_buf.data());
  348. auto const len = buffer_bytes(cb);
  349. BHO_ASSERT(len == impl.rd_fh.len);
  350. BHO_ASSERT(! impl.rd_close);
  351. impl.rd_close = true;
  352. close_reason cr;
  353. detail::read_close(cr, cb, result_);
  354. if(result_)
  355. {
  356. // _Fail the WebSocket Connection_
  357. code_ = close_code::protocol_error;
  358. goto close;
  359. }
  360. impl.cr = cr;
  361. impl.rd_buf.consume(len);
  362. if(impl.ctrl_cb)
  363. impl.ctrl_cb(frame_type::close,
  364. to_string_view(impl.cr.reason));
  365. // See if we are already closing
  366. if(impl.status_ == status::closing)
  367. {
  368. // _Close the WebSocket Connection_
  369. BHO_ASSERT(impl.wr_close);
  370. code_ = close_code::none;
  371. result_ = error::closed;
  372. goto close;
  373. }
  374. // _Start the WebSocket Closing Handshake_
  375. code_ = cr.code == close_code::none ?
  376. close_code::normal :
  377. static_cast<close_code>(cr.code);
  378. result_ = error::closed;
  379. goto close;
  380. }
  381. }
  382. if(impl.rd_fh.len == 0 && ! impl.rd_fh.fin)
  383. {
  384. // Empty non-final frame
  385. goto loop;
  386. }
  387. impl.rd_done = false;
  388. }
  389. if(! impl.rd_deflated())
  390. {
  391. if(impl.rd_remain > 0)
  392. {
  393. if(impl.rd_buf.size() == 0 && impl.rd_buf.max_size() >
  394. (std::min)(clamp(impl.rd_remain),
  395. buffer_bytes(cb_)))
  396. {
  397. // Fill the read buffer first, otherwise we
  398. // get fewer bytes at the cost of one I/O.
  399. ASIO_CORO_YIELD
  400. {
  401. ASIO_HANDLER_LOCATION((
  402. __FILE__, __LINE__,
  403. "websocket::async_read_some"));
  404. impl.stream().async_read_some(
  405. impl.rd_buf.prepare(read_size(
  406. impl.rd_buf, impl.rd_buf.max_size())),
  407. std::move(*this));
  408. }
  409. impl.rd_buf.commit(bytes_transferred);
  410. if(impl.check_stop_now(ec))
  411. goto upcall;
  412. impl.reset_idle();
  413. if(impl.rd_fh.mask)
  414. detail::mask_inplace(buffers_prefix(clamp(
  415. impl.rd_remain), impl.rd_buf.data()),
  416. impl.rd_key);
  417. }
  418. if(impl.rd_buf.size() > 0)
  419. {
  420. // Copy from the read buffer.
  421. // The mask was already applied.
  422. bytes_transferred = net::buffer_copy(cb_,
  423. impl.rd_buf.data(), clamp(impl.rd_remain));
  424. auto const mb = buffers_prefix(
  425. bytes_transferred, cb_);
  426. impl.rd_remain -= bytes_transferred;
  427. if(impl.rd_op == detail::opcode::text)
  428. {
  429. if(! impl.rd_utf8.write(mb) ||
  430. (impl.rd_remain == 0 && impl.rd_fh.fin &&
  431. ! impl.rd_utf8.finish()))
  432. {
  433. // _Fail the WebSocket Connection_
  434. code_ = close_code::bad_payload;
  435. result_ = error::bad_frame_payload;
  436. goto close;
  437. }
  438. }
  439. bytes_written_ += bytes_transferred;
  440. impl.rd_size += bytes_transferred;
  441. impl.rd_buf.consume(bytes_transferred);
  442. }
  443. else
  444. {
  445. // Read into caller's buffer
  446. BHO_ASSERT(impl.rd_remain > 0);
  447. BHO_ASSERT(buffer_bytes(cb_) > 0);
  448. BHO_ASSERT(buffer_bytes(buffers_prefix(
  449. clamp(impl.rd_remain), cb_)) > 0);
  450. ASIO_CORO_YIELD
  451. {
  452. ASIO_HANDLER_LOCATION((
  453. __FILE__, __LINE__,
  454. "websocket::async_read_some"));
  455. impl.stream().async_read_some(buffers_prefix(
  456. clamp(impl.rd_remain), cb_), std::move(*this));
  457. }
  458. if(impl.check_stop_now(ec))
  459. goto upcall;
  460. impl.reset_idle();
  461. BHO_ASSERT(bytes_transferred > 0);
  462. auto const mb = buffers_prefix(
  463. bytes_transferred, cb_);
  464. impl.rd_remain -= bytes_transferred;
  465. if(impl.rd_fh.mask)
  466. detail::mask_inplace(mb, impl.rd_key);
  467. if(impl.rd_op == detail::opcode::text)
  468. {
  469. if(! impl.rd_utf8.write(mb) ||
  470. (impl.rd_remain == 0 && impl.rd_fh.fin &&
  471. ! impl.rd_utf8.finish()))
  472. {
  473. // _Fail the WebSocket Connection_
  474. code_ = close_code::bad_payload;
  475. result_ = error::bad_frame_payload;
  476. goto close;
  477. }
  478. }
  479. bytes_written_ += bytes_transferred;
  480. impl.rd_size += bytes_transferred;
  481. }
  482. }
  483. BHO_ASSERT( ! impl.rd_done );
  484. if( impl.rd_remain == 0 && impl.rd_fh.fin )
  485. impl.rd_done = true;
  486. }
  487. else
  488. {
  489. // Read compressed message frame payload:
  490. // inflate even if rd_fh_.len == 0, otherwise we
  491. // never emit the end-of-stream deflate block.
  492. while(buffer_bytes(cb_) > 0)
  493. {
  494. if( impl.rd_remain > 0 &&
  495. impl.rd_buf.size() == 0 &&
  496. ! did_read_)
  497. {
  498. // read new
  499. ASIO_CORO_YIELD
  500. {
  501. ASIO_HANDLER_LOCATION((
  502. __FILE__, __LINE__,
  503. "websocket::async_read_some"));
  504. impl.stream().async_read_some(
  505. impl.rd_buf.prepare(read_size(
  506. impl.rd_buf, impl.rd_buf.max_size())),
  507. std::move(*this));
  508. }
  509. if(impl.check_stop_now(ec))
  510. goto upcall;
  511. impl.reset_idle();
  512. BHO_ASSERT(bytes_transferred > 0);
  513. impl.rd_buf.commit(bytes_transferred);
  514. if(impl.rd_fh.mask)
  515. detail::mask_inplace(
  516. buffers_prefix(clamp(impl.rd_remain),
  517. impl.rd_buf.data()), impl.rd_key);
  518. did_read_ = true;
  519. }
  520. zlib::z_params zs;
  521. {
  522. auto const out = buffers_front(cb_);
  523. zs.next_out = out.data();
  524. zs.avail_out = out.size();
  525. BHO_ASSERT(zs.avail_out > 0);
  526. }
  527. // boolean to track the end of the message.
  528. bool fin = false;
  529. if(impl.rd_remain > 0)
  530. {
  531. if(impl.rd_buf.size() > 0)
  532. {
  533. // use what's there
  534. auto const in = buffers_prefix(
  535. clamp(impl.rd_remain), buffers_front(
  536. impl.rd_buf.data()));
  537. zs.avail_in = in.size();
  538. zs.next_in = in.data();
  539. }
  540. else
  541. {
  542. break;
  543. }
  544. }
  545. else if(impl.rd_fh.fin)
  546. {
  547. // append the empty block codes
  548. static std::uint8_t constexpr
  549. empty_block[4] = { 0x00, 0x00, 0xff, 0xff };
  550. zs.next_in = empty_block;
  551. zs.avail_in = sizeof(empty_block);
  552. fin = true;
  553. }
  554. else
  555. {
  556. break;
  557. }
  558. impl.inflate(zs, zlib::Flush::sync, ec);
  559. if(impl.check_stop_now(ec))
  560. goto upcall;
  561. if(fin && zs.total_out == 0) {
  562. impl.do_context_takeover_read(impl.role);
  563. impl.rd_done = true;
  564. break;
  565. }
  566. if(impl.rd_msg_max && beast::detail::sum_exceeds(
  567. impl.rd_size, zs.total_out, impl.rd_msg_max))
  568. {
  569. // _Fail the WebSocket Connection_
  570. code_ = close_code::too_big;
  571. result_ = error::message_too_big;
  572. goto close;
  573. }
  574. cb_.consume(zs.total_out);
  575. impl.rd_size += zs.total_out;
  576. if (! fin) {
  577. impl.rd_remain -= zs.total_in;
  578. impl.rd_buf.consume(zs.total_in);
  579. }
  580. bytes_written_ += zs.total_out;
  581. }
  582. if(impl.rd_op == detail::opcode::text)
  583. {
  584. // check utf8
  585. if(! impl.rd_utf8.write(
  586. buffers_prefix(bytes_written_, bs_)) || (
  587. impl.rd_done && ! impl.rd_utf8.finish()))
  588. {
  589. // _Fail the WebSocket Connection_
  590. code_ = close_code::bad_payload;
  591. result_ = error::bad_frame_payload;
  592. goto close;
  593. }
  594. }
  595. }
  596. goto upcall;
  597. close:
  598. // Acquire the write lock
  599. if(! impl.wr_block.try_lock(this))
  600. {
  601. ASIO_CORO_YIELD
  602. {
  603. ASIO_HANDLER_LOCATION((
  604. __FILE__, __LINE__,
  605. "websocket::async_read_some"));
  606. impl.op_rd.emplace(std::move(*this));
  607. }
  608. if (ec)
  609. return this->complete(cont, ec, bytes_written_);
  610. impl.wr_block.lock(this);
  611. ASIO_CORO_YIELD
  612. {
  613. ASIO_HANDLER_LOCATION((
  614. __FILE__, __LINE__,
  615. "websocket::async_read_some"));
  616. const auto ex = this->get_immediate_executor();
  617. net::dispatch(ex, std::move(*this));
  618. }
  619. BHO_ASSERT(impl.wr_block.is_locked(this));
  620. if(impl.check_stop_now(ec))
  621. goto upcall;
  622. }
  623. impl.change_status(status::closing);
  624. if(! impl.wr_close)
  625. {
  626. impl.wr_close = true;
  627. // Serialize close frame
  628. impl.rd_fb.clear();
  629. impl.template write_close<
  630. flat_static_buffer_base>(
  631. impl.rd_fb, code_);
  632. // Send close frame
  633. BHO_ASSERT(impl.wr_block.is_locked(this));
  634. ASIO_CORO_YIELD
  635. {
  636. ASIO_HANDLER_LOCATION((
  637. __FILE__, __LINE__,
  638. "websocket::async_read_some"));
  639. net::async_write(impl.stream(), net::const_buffer(impl.rd_fb.data()),
  640. beast::detail::bind_continuation(std::move(*this)));
  641. }
  642. BHO_ASSERT(impl.wr_block.is_locked(this));
  643. if(impl.check_stop_now(ec))
  644. goto upcall;
  645. }
  646. // Teardown
  647. using beast::websocket::async_teardown;
  648. BHO_ASSERT(impl.wr_block.is_locked(this));
  649. ASIO_CORO_YIELD
  650. {
  651. ASIO_HANDLER_LOCATION((
  652. __FILE__, __LINE__,
  653. "websocket::async_read_some"));
  654. async_teardown(impl.role, impl.stream(),
  655. beast::detail::bind_continuation(std::move(*this)));
  656. }
  657. BHO_ASSERT(impl.wr_block.is_locked(this));
  658. if(ec == net::error::eof)
  659. {
  660. // Rationale:
  661. // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
  662. ec = {};
  663. }
  664. if(! ec)
  665. {
  666. BHO_BEAST_ASSIGN_EC(ec, result_);
  667. }
  668. if(ec && ec != error::closed)
  669. impl.change_status(status::failed);
  670. else
  671. impl.change_status(status::closed);
  672. impl.close();
  673. upcall:
  674. impl.rd_block.try_unlock(this);
  675. impl.op_r_close.maybe_invoke();
  676. if(impl.wr_block.try_unlock(this))
  677. impl.op_close.maybe_invoke()
  678. || impl.op_idle_ping.maybe_invoke()
  679. || impl.op_ping.maybe_invoke()
  680. || impl.op_wr.maybe_invoke();
  681. this->complete(cont, ec, bytes_written_);
  682. }
  683. }
  684. };
  685. //------------------------------------------------------------------------------
  686. template<class NextLayer, bool deflateSupported>
  687. template<class Handler, class DynamicBuffer>
  688. class stream<NextLayer, deflateSupported>::read_op
  689. : public beast::async_base<
  690. Handler, beast::executor_type<stream>>
  691. , public asio::coroutine
  692. {
  693. std::weak_ptr<impl_type> wp_;
  694. DynamicBuffer& b_;
  695. std::size_t limit_;
  696. std::size_t bytes_written_ = 0;
  697. bool some_;
  698. public:
  699. template<class Handler_>
  700. read_op(
  701. Handler_&& h,
  702. std::shared_ptr<impl_type> const& sp,
  703. DynamicBuffer& b,
  704. std::size_t limit,
  705. bool some)
  706. : async_base<Handler,
  707. beast::executor_type<stream>>(
  708. std::forward<Handler_>(h),
  709. sp->stream().get_executor())
  710. , wp_(sp)
  711. , b_(b)
  712. , limit_(limit ? limit : (
  713. std::numeric_limits<std::size_t>::max)())
  714. , some_(some)
  715. {
  716. (*this)({}, 0, false);
  717. }
  718. void operator()(
  719. error_code ec = {},
  720. std::size_t bytes_transferred = 0,
  721. bool cont = true)
  722. {
  723. using beast::detail::clamp;
  724. auto sp = wp_.lock();
  725. if(! sp)
  726. {
  727. BHO_BEAST_ASSIGN_EC(ec, net::error::operation_aborted);
  728. bytes_written_ = 0;
  729. return this->complete(cont, ec, bytes_written_);
  730. }
  731. auto& impl = *sp;
  732. using mutable_buffers_type = typename
  733. DynamicBuffer::mutable_buffers_type;
  734. ASIO_CORO_REENTER(*this)
  735. {
  736. do
  737. {
  738. // VFALCO TODO use bho::beast::bind_continuation
  739. ASIO_CORO_YIELD
  740. {
  741. auto mb = beast::detail::dynamic_buffer_prepare(b_,
  742. clamp(impl.read_size_hint_db(b_), limit_),
  743. ec, error::buffer_overflow);
  744. if(impl.check_stop_now(ec))
  745. goto upcall;
  746. ASIO_HANDLER_LOCATION((
  747. __FILE__, __LINE__,
  748. "websocket::async_read"));
  749. read_some_op<read_op, mutable_buffers_type>(
  750. std::move(*this), sp, *mb);
  751. }
  752. b_.commit(bytes_transferred);
  753. bytes_written_ += bytes_transferred;
  754. if(ec)
  755. goto upcall;
  756. }
  757. while(! some_ && ! impl.rd_done);
  758. upcall:
  759. this->complete(cont, ec, bytes_written_);
  760. }
  761. }
  762. };
  763. template<class NextLayer, bool deflateSupported>
  764. struct stream<NextLayer, deflateSupported>::
  765. run_read_some_op
  766. {
  767. template<
  768. class ReadHandler,
  769. class MutableBufferSequence>
  770. void
  771. operator()(
  772. ReadHandler&& h,
  773. std::shared_ptr<impl_type> const& sp,
  774. MutableBufferSequence const& b)
  775. {
  776. // If you get an error on the following line it means
  777. // that your handler does not meet the documented type
  778. // requirements for the handler.
  779. static_assert(
  780. beast::detail::is_invocable<ReadHandler,
  781. void(error_code, std::size_t)>::value,
  782. "ReadHandler type requirements not met");
  783. read_some_op<
  784. typename std::decay<ReadHandler>::type,
  785. MutableBufferSequence>(
  786. std::forward<ReadHandler>(h),
  787. sp,
  788. b);
  789. }
  790. };
  791. template<class NextLayer, bool deflateSupported>
  792. struct stream<NextLayer, deflateSupported>::
  793. run_read_op
  794. {
  795. template<
  796. class ReadHandler,
  797. class DynamicBuffer>
  798. void
  799. operator()(
  800. ReadHandler&& h,
  801. std::shared_ptr<impl_type> const& sp,
  802. DynamicBuffer* b,
  803. std::size_t limit,
  804. bool some)
  805. {
  806. // If you get an error on the following line it means
  807. // that your handler does not meet the documented type
  808. // requirements for the handler.
  809. static_assert(
  810. beast::detail::is_invocable<ReadHandler,
  811. void(error_code, std::size_t)>::value,
  812. "ReadHandler type requirements not met");
  813. read_op<
  814. typename std::decay<ReadHandler>::type,
  815. DynamicBuffer>(
  816. std::forward<ReadHandler>(h),
  817. sp,
  818. *b,
  819. limit,
  820. some);
  821. }
  822. };
  823. //------------------------------------------------------------------------------
  824. template<class NextLayer, bool deflateSupported>
  825. template<class DynamicBuffer>
  826. std::size_t
  827. stream<NextLayer, deflateSupported>::
  828. read(DynamicBuffer& buffer)
  829. {
  830. static_assert(is_sync_stream<next_layer_type>::value,
  831. "SyncStream type requirements not met");
  832. static_assert(
  833. net::is_dynamic_buffer<DynamicBuffer>::value,
  834. "DynamicBuffer type requirements not met");
  835. error_code ec;
  836. auto const bytes_written = read(buffer, ec);
  837. if(ec)
  838. BHO_THROW_EXCEPTION(system_error{ec});
  839. return bytes_written;
  840. }
  841. template<class NextLayer, bool deflateSupported>
  842. template<class DynamicBuffer>
  843. std::size_t
  844. stream<NextLayer, deflateSupported>::
  845. read(DynamicBuffer& buffer, error_code& ec)
  846. {
  847. static_assert(is_sync_stream<next_layer_type>::value,
  848. "SyncStream type requirements not met");
  849. static_assert(
  850. net::is_dynamic_buffer<DynamicBuffer>::value,
  851. "DynamicBuffer type requirements not met");
  852. std::size_t bytes_written = 0;
  853. do
  854. {
  855. bytes_written += read_some(buffer, 0, ec);
  856. if(ec)
  857. return bytes_written;
  858. }
  859. while(! is_message_done());
  860. return bytes_written;
  861. }
  862. template<class NextLayer, bool deflateSupported>
  863. template<class DynamicBuffer, BHO_BEAST_ASYNC_TPARAM2 ReadHandler>
  864. BHO_BEAST_ASYNC_RESULT2(ReadHandler)
  865. stream<NextLayer, deflateSupported>::
  866. async_read(DynamicBuffer& buffer, ReadHandler&& handler)
  867. {
  868. static_assert(is_async_stream<next_layer_type>::value,
  869. "AsyncStream type requirements not met");
  870. static_assert(
  871. net::is_dynamic_buffer<DynamicBuffer>::value,
  872. "DynamicBuffer type requirements not met");
  873. return net::async_initiate<
  874. ReadHandler,
  875. void(error_code, std::size_t)>(
  876. run_read_op{},
  877. handler,
  878. impl_,
  879. &buffer,
  880. 0,
  881. false);
  882. }
  883. //------------------------------------------------------------------------------
  884. template<class NextLayer, bool deflateSupported>
  885. template<class DynamicBuffer>
  886. std::size_t
  887. stream<NextLayer, deflateSupported>::
  888. read_some(
  889. DynamicBuffer& buffer,
  890. std::size_t limit)
  891. {
  892. static_assert(is_sync_stream<next_layer_type>::value,
  893. "SyncStream type requirements not met");
  894. static_assert(
  895. net::is_dynamic_buffer<DynamicBuffer>::value,
  896. "DynamicBuffer type requirements not met");
  897. error_code ec;
  898. auto const bytes_written =
  899. read_some(buffer, limit, ec);
  900. if(ec)
  901. BHO_THROW_EXCEPTION(system_error{ec});
  902. return bytes_written;
  903. }
  904. template<class NextLayer, bool deflateSupported>
  905. template<class DynamicBuffer>
  906. std::size_t
  907. stream<NextLayer, deflateSupported>::
  908. read_some(
  909. DynamicBuffer& buffer,
  910. std::size_t limit,
  911. error_code& ec)
  912. {
  913. static_assert(is_sync_stream<next_layer_type>::value,
  914. "SyncStream type requirements not met");
  915. static_assert(
  916. net::is_dynamic_buffer<DynamicBuffer>::value,
  917. "DynamicBuffer type requirements not met");
  918. using beast::detail::clamp;
  919. if(! limit)
  920. limit = (std::numeric_limits<std::size_t>::max)();
  921. auto const size =
  922. clamp(read_size_hint(buffer), limit);
  923. BHO_ASSERT(size > 0);
  924. auto mb = beast::detail::dynamic_buffer_prepare(
  925. buffer, size, ec, error::buffer_overflow);
  926. if(impl_->check_stop_now(ec))
  927. return 0;
  928. auto const bytes_written = read_some(*mb, ec);
  929. buffer.commit(bytes_written);
  930. return bytes_written;
  931. }
  932. template<class NextLayer, bool deflateSupported>
  933. template<class DynamicBuffer, BHO_BEAST_ASYNC_TPARAM2 ReadHandler>
  934. BHO_BEAST_ASYNC_RESULT2(ReadHandler)
  935. stream<NextLayer, deflateSupported>::
  936. async_read_some(
  937. DynamicBuffer& buffer,
  938. std::size_t limit,
  939. ReadHandler&& handler)
  940. {
  941. static_assert(is_async_stream<next_layer_type>::value,
  942. "AsyncStream type requirements not met");
  943. static_assert(
  944. net::is_dynamic_buffer<DynamicBuffer>::value,
  945. "DynamicBuffer type requirements not met");
  946. return net::async_initiate<
  947. ReadHandler,
  948. void(error_code, std::size_t)>(
  949. run_read_op{},
  950. handler,
  951. impl_,
  952. &buffer,
  953. limit,
  954. true);
  955. }
  956. //------------------------------------------------------------------------------
  957. template<class NextLayer, bool deflateSupported>
  958. template<class MutableBufferSequence>
  959. std::size_t
  960. stream<NextLayer, deflateSupported>::
  961. read_some(
  962. MutableBufferSequence const& buffers)
  963. {
  964. static_assert(is_sync_stream<next_layer_type>::value,
  965. "SyncStream type requirements not met");
  966. static_assert(net::is_mutable_buffer_sequence<
  967. MutableBufferSequence>::value,
  968. "MutableBufferSequence type requirements not met");
  969. error_code ec;
  970. auto const bytes_written = read_some(buffers, ec);
  971. if(ec)
  972. BHO_THROW_EXCEPTION(system_error{ec});
  973. return bytes_written;
  974. }
  975. template<class NextLayer, bool deflateSupported>
  976. template<class MutableBufferSequence>
  977. std::size_t
  978. stream<NextLayer, deflateSupported>::
  979. read_some(
  980. MutableBufferSequence const& buffers,
  981. error_code& ec)
  982. {
  983. static_assert(is_sync_stream<next_layer_type>::value,
  984. "SyncStream type requirements not met");
  985. static_assert(net::is_mutable_buffer_sequence<
  986. MutableBufferSequence>::value,
  987. "MutableBufferSequence type requirements not met");
  988. using beast::detail::clamp;
  989. auto& impl = *impl_;
  990. close_code code{};
  991. std::size_t bytes_written = 0;
  992. ec = {};
  993. // Make sure the stream is open
  994. if(impl.check_stop_now(ec))
  995. return bytes_written;
  996. loop:
  997. // See if we need to read a frame header. This
  998. // condition is structured to give the decompressor
  999. // a chance to emit the final empty deflate block
  1000. //
  1001. if(impl.rd_remain == 0 && (
  1002. ! impl.rd_fh.fin || impl.rd_done))
  1003. {
  1004. // Read frame header
  1005. error_code result;
  1006. while(! impl.parse_fh(impl.rd_fh, impl.rd_buf, result))
  1007. {
  1008. if(result)
  1009. {
  1010. // _Fail the WebSocket Connection_
  1011. if(result == error::message_too_big)
  1012. code = close_code::too_big;
  1013. else
  1014. code = close_code::protocol_error;
  1015. do_fail(code, result, ec);
  1016. return bytes_written;
  1017. }
  1018. auto const bytes_transferred =
  1019. impl.stream().read_some(
  1020. impl.rd_buf.prepare(read_size(
  1021. impl.rd_buf, impl.rd_buf.max_size())),
  1022. ec);
  1023. impl.rd_buf.commit(bytes_transferred);
  1024. if(impl.check_stop_now(ec))
  1025. return bytes_written;
  1026. }
  1027. // Immediately apply the mask to the portion
  1028. // of the buffer holding payload data.
  1029. if(impl.rd_fh.len > 0 && impl.rd_fh.mask)
  1030. detail::mask_inplace(buffers_prefix(
  1031. clamp(impl.rd_fh.len), impl.rd_buf.data()),
  1032. impl.rd_key);
  1033. if(detail::is_control(impl.rd_fh.op))
  1034. {
  1035. // Get control frame payload
  1036. auto const b = buffers_prefix(
  1037. clamp(impl.rd_fh.len), impl.rd_buf.data());
  1038. auto const len = buffer_bytes(b);
  1039. BHO_ASSERT(len == impl.rd_fh.len);
  1040. // Clear this otherwise the next
  1041. // frame will be considered final.
  1042. impl.rd_fh.fin = false;
  1043. // Handle ping frame
  1044. if(impl.rd_fh.op == detail::opcode::ping)
  1045. {
  1046. ping_data payload;
  1047. detail::read_ping(payload, b);
  1048. impl.rd_buf.consume(len);
  1049. if(impl.wr_close)
  1050. {
  1051. // Ignore ping when closing
  1052. goto loop;
  1053. }
  1054. if(impl.ctrl_cb)
  1055. impl.ctrl_cb(frame_type::ping, to_string_view(payload));
  1056. detail::frame_buffer fb;
  1057. impl.template write_ping<flat_static_buffer_base>(fb,
  1058. detail::opcode::pong, payload);
  1059. net::write(impl.stream(), fb.data(), ec);
  1060. if(impl.check_stop_now(ec))
  1061. return bytes_written;
  1062. goto loop;
  1063. }
  1064. // Handle pong frame
  1065. if(impl.rd_fh.op == detail::opcode::pong)
  1066. {
  1067. ping_data payload;
  1068. detail::read_ping(payload, b);
  1069. impl.rd_buf.consume(len);
  1070. if(impl.ctrl_cb)
  1071. impl.ctrl_cb(frame_type::pong, to_string_view(payload));
  1072. goto loop;
  1073. }
  1074. // Handle close frame
  1075. BHO_ASSERT(impl.rd_fh.op == detail::opcode::close);
  1076. {
  1077. BHO_ASSERT(! impl.rd_close);
  1078. impl.rd_close = true;
  1079. close_reason cr;
  1080. detail::read_close(cr, b, result);
  1081. if(result)
  1082. {
  1083. // _Fail the WebSocket Connection_
  1084. do_fail(close_code::protocol_error,
  1085. result, ec);
  1086. return bytes_written;
  1087. }
  1088. impl.cr = cr;
  1089. impl.rd_buf.consume(len);
  1090. if(impl.ctrl_cb)
  1091. impl.ctrl_cb(frame_type::close, to_string_view(impl.cr.reason));
  1092. BHO_ASSERT(! impl.wr_close);
  1093. // _Start the WebSocket Closing Handshake_
  1094. do_fail(
  1095. cr.code == close_code::none ?
  1096. close_code::normal :
  1097. static_cast<close_code>(cr.code),
  1098. error::closed, ec);
  1099. return bytes_written;
  1100. }
  1101. }
  1102. if(impl.rd_fh.len == 0 && ! impl.rd_fh.fin)
  1103. {
  1104. // Empty non-final frame
  1105. goto loop;
  1106. }
  1107. impl.rd_done = false;
  1108. }
  1109. else
  1110. {
  1111. ec = {};
  1112. }
  1113. if(! impl.rd_deflated())
  1114. {
  1115. if(impl.rd_remain > 0)
  1116. {
  1117. if(impl.rd_buf.size() == 0 && impl.rd_buf.max_size() >
  1118. (std::min)(clamp(impl.rd_remain),
  1119. buffer_bytes(buffers)))
  1120. {
  1121. // Fill the read buffer first, otherwise we
  1122. // get fewer bytes at the cost of one I/O.
  1123. impl.rd_buf.commit(impl.stream().read_some(
  1124. impl.rd_buf.prepare(read_size(impl.rd_buf,
  1125. impl.rd_buf.max_size())), ec));
  1126. if(impl.check_stop_now(ec))
  1127. return bytes_written;
  1128. if(impl.rd_fh.mask)
  1129. detail::mask_inplace(
  1130. buffers_prefix(clamp(impl.rd_remain),
  1131. impl.rd_buf.data()), impl.rd_key);
  1132. }
  1133. if(impl.rd_buf.size() > 0)
  1134. {
  1135. // Copy from the read buffer.
  1136. // The mask was already applied.
  1137. auto const bytes_transferred = net::buffer_copy(
  1138. buffers, impl.rd_buf.data(),
  1139. clamp(impl.rd_remain));
  1140. auto const mb = buffers_prefix(
  1141. bytes_transferred, buffers);
  1142. impl.rd_remain -= bytes_transferred;
  1143. if(impl.rd_op == detail::opcode::text)
  1144. {
  1145. if(! impl.rd_utf8.write(mb) ||
  1146. (impl.rd_remain == 0 && impl.rd_fh.fin &&
  1147. ! impl.rd_utf8.finish()))
  1148. {
  1149. // _Fail the WebSocket Connection_
  1150. do_fail(close_code::bad_payload,
  1151. error::bad_frame_payload, ec);
  1152. return bytes_written;
  1153. }
  1154. }
  1155. bytes_written += bytes_transferred;
  1156. impl.rd_size += bytes_transferred;
  1157. impl.rd_buf.consume(bytes_transferred);
  1158. }
  1159. else
  1160. {
  1161. // Read into caller's buffer
  1162. BHO_ASSERT(impl.rd_remain > 0);
  1163. BHO_ASSERT(buffer_bytes(buffers) > 0);
  1164. BHO_ASSERT(buffer_bytes(buffers_prefix(
  1165. clamp(impl.rd_remain), buffers)) > 0);
  1166. auto const bytes_transferred =
  1167. impl.stream().read_some(buffers_prefix(
  1168. clamp(impl.rd_remain), buffers), ec);
  1169. // VFALCO What if some bytes were written?
  1170. if(impl.check_stop_now(ec))
  1171. return bytes_written;
  1172. BHO_ASSERT(bytes_transferred > 0);
  1173. auto const mb = buffers_prefix(
  1174. bytes_transferred, buffers);
  1175. impl.rd_remain -= bytes_transferred;
  1176. if(impl.rd_fh.mask)
  1177. detail::mask_inplace(mb, impl.rd_key);
  1178. if(impl.rd_op == detail::opcode::text)
  1179. {
  1180. if(! impl.rd_utf8.write(mb) ||
  1181. (impl.rd_remain == 0 && impl.rd_fh.fin &&
  1182. ! impl.rd_utf8.finish()))
  1183. {
  1184. // _Fail the WebSocket Connection_
  1185. do_fail(close_code::bad_payload,
  1186. error::bad_frame_payload, ec);
  1187. return bytes_written;
  1188. }
  1189. }
  1190. bytes_written += bytes_transferred;
  1191. impl.rd_size += bytes_transferred;
  1192. }
  1193. }
  1194. BHO_ASSERT( ! impl.rd_done );
  1195. if( impl.rd_remain == 0 && impl.rd_fh.fin )
  1196. impl.rd_done = true;
  1197. }
  1198. else
  1199. {
  1200. // Read compressed message frame payload:
  1201. // inflate even if rd_fh_.len == 0, otherwise we
  1202. // never emit the end-of-stream deflate block.
  1203. //
  1204. bool did_read = false;
  1205. buffers_suffix<MutableBufferSequence> cb(buffers);
  1206. while(buffer_bytes(cb) > 0)
  1207. {
  1208. zlib::z_params zs;
  1209. {
  1210. auto const out = beast::buffers_front(cb);
  1211. zs.next_out = out.data();
  1212. zs.avail_out = out.size();
  1213. BHO_ASSERT(zs.avail_out > 0);
  1214. }
  1215. // boolean to track the end of the message.
  1216. bool fin = false;
  1217. if(impl.rd_remain > 0)
  1218. {
  1219. if(impl.rd_buf.size() > 0)
  1220. {
  1221. // use what's there
  1222. auto const in = buffers_prefix(
  1223. clamp(impl.rd_remain), beast::buffers_front(
  1224. impl.rd_buf.data()));
  1225. zs.avail_in = in.size();
  1226. zs.next_in = in.data();
  1227. }
  1228. else if(! did_read)
  1229. {
  1230. // read new
  1231. auto const bytes_transferred =
  1232. impl.stream().read_some(
  1233. impl.rd_buf.prepare(read_size(
  1234. impl.rd_buf, impl.rd_buf.max_size())),
  1235. ec);
  1236. if(impl.check_stop_now(ec))
  1237. return bytes_written;
  1238. BHO_ASSERT(bytes_transferred > 0);
  1239. impl.rd_buf.commit(bytes_transferred);
  1240. if(impl.rd_fh.mask)
  1241. detail::mask_inplace(
  1242. buffers_prefix(clamp(impl.rd_remain),
  1243. impl.rd_buf.data()), impl.rd_key);
  1244. auto const in = buffers_prefix(
  1245. clamp(impl.rd_remain), buffers_front(
  1246. impl.rd_buf.data()));
  1247. zs.avail_in = in.size();
  1248. zs.next_in = in.data();
  1249. did_read = true;
  1250. }
  1251. else
  1252. {
  1253. break;
  1254. }
  1255. }
  1256. else if(impl.rd_fh.fin)
  1257. {
  1258. // append the empty block codes
  1259. static std::uint8_t constexpr
  1260. empty_block[4] = { 0x00, 0x00, 0xff, 0xff };
  1261. zs.next_in = empty_block;
  1262. zs.avail_in = sizeof(empty_block);
  1263. fin = true;
  1264. }
  1265. else
  1266. {
  1267. break;
  1268. }
  1269. impl.inflate(zs, zlib::Flush::sync, ec);
  1270. if(impl.check_stop_now(ec))
  1271. return bytes_written;
  1272. if (fin && zs.total_out == 0) {
  1273. impl.do_context_takeover_read(impl.role);
  1274. impl.rd_done = true;
  1275. break;
  1276. }
  1277. if(impl.rd_msg_max && beast::detail::sum_exceeds(
  1278. impl.rd_size, zs.total_out, impl.rd_msg_max))
  1279. {
  1280. do_fail(close_code::too_big,
  1281. error::message_too_big, ec);
  1282. return bytes_written;
  1283. }
  1284. cb.consume(zs.total_out);
  1285. impl.rd_size += zs.total_out;
  1286. if (! fin) {
  1287. impl.rd_remain -= zs.total_in;
  1288. impl.rd_buf.consume(zs.total_in);
  1289. }
  1290. bytes_written += zs.total_out;
  1291. }
  1292. if(impl.rd_op == detail::opcode::text)
  1293. {
  1294. // check utf8
  1295. if(! impl.rd_utf8.write(beast::buffers_prefix(
  1296. bytes_written, buffers)) || (
  1297. impl.rd_done && ! impl.rd_utf8.finish()))
  1298. {
  1299. // _Fail the WebSocket Connection_
  1300. do_fail(close_code::bad_payload,
  1301. error::bad_frame_payload, ec);
  1302. return bytes_written;
  1303. }
  1304. }
  1305. }
  1306. return bytes_written;
  1307. }
  1308. template<class NextLayer, bool deflateSupported>
  1309. template<class MutableBufferSequence, BHO_BEAST_ASYNC_TPARAM2 ReadHandler>
  1310. BHO_BEAST_ASYNC_RESULT2(ReadHandler)
  1311. stream<NextLayer, deflateSupported>::
  1312. async_read_some(
  1313. MutableBufferSequence const& buffers,
  1314. ReadHandler&& handler)
  1315. {
  1316. static_assert(is_async_stream<next_layer_type>::value,
  1317. "AsyncStream type requirements not met");
  1318. static_assert(net::is_mutable_buffer_sequence<
  1319. MutableBufferSequence>::value,
  1320. "MutableBufferSequence type requirements not met");
  1321. return net::async_initiate<
  1322. ReadHandler,
  1323. void(error_code, std::size_t)>(
  1324. run_read_some_op{},
  1325. handler,
  1326. impl_,
  1327. buffers);
  1328. }
  1329. } // websocket
  1330. } // beast
  1331. } // bho
  1332. #endif