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