2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
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)
7 // Official repository: https://github.com/boostorg/beast
10 #ifndef BOOST_BEAST_WEBSOCKET_IMPL_STREAM_IMPL_HPP
11 #define BOOST_BEAST_WEBSOCKET_IMPL_STREAM_IMPL_HPP
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/beast/version.hpp>
34 #include <boost/asio/steady_timer.hpp>
35 #include <boost/core/empty_value.hpp>
36 #include <boost/enable_shared_from_this.hpp>
37 #include <boost/shared_ptr.hpp>
38 #include <boost/optional.hpp>
45 class NextLayer, bool deflateSupported>
46 struct stream<NextLayer, deflateSupported>::impl_type
47 : boost::empty_value<NextLayer>
48 , detail::service::impl_type
49 , detail::impl_base<deflateSupported>
51 NextLayer& stream() noexcept
53 return this->boost::empty_value<
57 boost::weak_ptr<impl_type>
60 return boost::static_pointer_cast<
61 impl_type>(this->detail::service::
62 impl_type::shared_from_this());
65 boost::shared_ptr<impl_type>
68 return boost::static_pointer_cast<
69 impl_type>(this->detail::service::
70 impl_type::shared_from_this());
73 net::steady_timer timer; // used for timeouts
74 close_reason cr; // set from received close frame
75 control_cb_type ctrl_cb; // control callback
77 std::size_t rd_msg_max /* max message size */ = 16 * 1024 * 1024;
78 std::uint64_t rd_size /* total size of current message so far */ = 0;
79 std::uint64_t rd_remain /* message frame bytes left in current frame */ = 0;
80 detail::frame_header rd_fh; // current frame header
81 detail::prepared_key rd_key; // current stateful mask key
82 detail::frame_buffer rd_fb; // to write control frames (during reads)
83 detail::utf8_checker rd_utf8; // to validate utf8
85 +tcp_frame_size> rd_buf; // buffer for reads
86 detail::opcode rd_op /* current message binary or text */ = detail::opcode::text;
87 bool rd_cont /* `true` if the next frame is a continuation */ = false;
88 bool rd_done /* set when a message is done */ = true;
89 bool rd_close /* did we read a close frame? */ = false;
90 detail::soft_mutex rd_block; // op currently reading
92 role_type role /* server or client */ = role_type::client;
93 status status_ /* state of the object */ = status::closed;
95 detail::soft_mutex wr_block; // op currently writing
96 bool wr_close /* did we write a close frame? */ = false;
97 bool wr_cont /* next write is a continuation */ = false;
98 bool wr_frag /* autofrag the current message */ = false;
99 bool wr_frag_opt /* autofrag option setting */ = true;
100 bool wr_compress; /* compress current message */
101 bool wr_compress_opt /* compress message setting */ = true;
102 detail::opcode wr_opcode /* message type */ = detail::opcode::text;
104 std::uint8_t[]> wr_buf; // write buffer
105 std::size_t wr_buf_size /* write buffer size (current message) */ = 0;
106 std::size_t wr_buf_opt /* write buffer size option setting */ = 4096;
107 detail::fh_buffer wr_fb; // header buffer used for writes
109 saved_handler op_rd; // paused read op
110 saved_handler op_wr; // paused write op
111 saved_handler op_ping; // paused ping op
112 saved_handler op_idle_ping; // paused idle ping op
113 saved_handler op_close; // paused close op
114 saved_handler op_r_rd; // paused read op (async read)
115 saved_handler op_r_close; // paused close op (async read)
117 bool idle_pinging = false;
118 bool secure_prng_ = true;
119 bool ec_delivered = false;
120 bool timed_out = false;
121 int idle_counter = 0;
123 detail::decorator decorator_opt; // Decorator for HTTP messages
124 timeout timeout_opt; // Timeout/idle settings
126 template<class... Args>
127 impl_type(Args&&... args)
128 : boost::empty_value<NextLayer>(
129 boost::empty_init_t{},
130 std::forward<Args>(args)...)
131 , detail::service::impl_type(
132 this->boost::empty_value<NextLayer>::get().get_executor().context())
133 , timer(this->boost::empty_value<NextLayer>::get().get_executor())
135 timeout_opt.handshake_timeout = none();
136 timeout_opt.idle_timeout = none();
137 timeout_opt.keep_alive_pings = false;
146 op_idle_ping.reset();
153 open(role_type role_)
155 // VFALCO TODO analyze and remove dupe code in reset()
156 timer.expires_at(never());
158 cr.code = close_code::none;
160 status_ = status::open;
164 // Can't clear this because accept uses it
169 // These should not be necessary, because all completion
170 // handlers must be allowed to execute otherwise the
171 // stream exhibits undefined behavior.
178 this->open_pmd(role);
192 BOOST_ASSERT(status_ != status::open);
193 timer.expires_at(never());
194 cr.code = close_code::none;
198 rd_buf.consume(rd_buf.size());
203 // These should not be necessary, because all completion
204 // handlers must be allowed to execute otherwise the
205 // stream exhibits undefined behavior.
209 // VFALCO Is this needed?
217 change_status(status::closed);
218 close_socket(get_lowest_layer(stream()));
221 // Called just before sending
222 // the first frame of each message
226 wr_frag = wr_frag_opt;
228 this->pmd_enabled() && wr_compress_opt;
230 // Maintain the write buffer
231 if( this->pmd_enabled() ||
232 role == role_type::client)
235 wr_buf_size != wr_buf_opt)
237 wr_buf_size = wr_buf_opt;
238 wr_buf = boost::make_unique_noinit<
239 std::uint8_t[]>(wr_buf_size);
244 wr_buf_size = wr_buf_opt;
251 //--------------------------------------------------------------------------
253 template<class Decorator>
256 detail::sec_ws_key_type& key,
257 string_view host, string_view target,
258 Decorator const& decorator);
262 response_type const& res,
263 detail::sec_ws_key_type const& key,
266 template<class Body, class Allocator, class Decorator>
270 http::basic_fields<Allocator>> const& req,
271 Decorator const& decorator,
274 // Attempt to read a complete frame header.
275 // Returns `false` if more bytes are needed
276 template<class DynamicBuffer>
278 parse_fh(detail::frame_header& fh,
279 DynamicBuffer& b, error_code& ec);
284 auto g = detail::make_prng(secure_prng_);
290 template<class DynamicBuffer>
292 read_size_hint_db(DynamicBuffer& buffer) const
294 auto const initial_size = (std::min)(
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);
303 template<class DynamicBuffer>
305 write_ping(DynamicBuffer& db,
306 detail::opcode code, ping_data const& data);
308 template<class DynamicBuffer>
310 write_close(DynamicBuffer& db, close_reason const& cr);
312 //--------------------------------------------------------------------------
315 set_option(timeout const& opt)
317 if( opt.handshake_timeout == none() &&
318 opt.idle_timeout == none())
322 timer.expires_at(never());
328 // Determine if an operation should stop and
329 // deliver an error code to the completion handler.
331 // This function must be called at the beginning
332 // of every composed operation, and every time a
333 // composed operation receives an intermediate
337 check_stop_now(error_code& ec)
339 // Deliver the timeout to the first caller
343 ec = beast::error::timeout;
347 // If the stream is closed then abort
348 if( status_ == status::closed ||
349 status_ == status::failed)
351 //BOOST_ASSERT(ec_delivered);
352 ec = net::error::operation_aborted;
356 // If no error then keep going
360 // Is this the first error seen?
364 ec = net::error::operation_aborted;
368 // Deliver the error to the completion handler
370 if(status_ != status::closed)
371 status_ = status::failed;
375 // Change the status of the stream
377 change_status(status new_status)
381 case status::handshake:
387 case status::closing:
388 //BOOST_ASSERT(status_ == status::open);
393 // this->close(); // Is this right?
399 status_ = new_status;
402 // Called to disarm the idle timeout counter
409 // Maintain the expiration timer
410 template<class Executor>
412 update_timer(Executor const& ex)
416 case status::handshake:
417 BOOST_ASSERT(idle_counter == 0);
418 if(! is_timer_set() &&
419 timeout_opt.handshake_timeout != none())
422 timeout_opt.handshake_timeout);
424 timeout_handler<Executor>(
425 ex, this->weak_from_this()));
430 if(timeout_opt.idle_timeout != none())
433 if(timeout_opt.keep_alive_pings)
435 timeout_opt.idle_timeout / 2);
438 timeout_opt.idle_timeout);
440 timeout_handler<Executor>(
441 ex, this->weak_from_this()));
446 timer.expires_at(never());
450 case status::closing:
451 if(timeout_opt.handshake_timeout != none())
455 timeout_opt.handshake_timeout);
457 timeout_handler<Executor>(
458 ex, this->weak_from_this()));
462 // VFALCO This assert goes off when there's also
463 // a pending read with the timer set. The bigger
464 // fix is to give close its own timeout, instead
465 // of using the handshake timeout.
466 // BOOST_ASSERT(! is_timer_set());
472 // this->close(); // Is this right?
474 timer.expires_at(never());
483 return timer.expiry() != never();
486 template<class Executor>
487 class timeout_handler
488 : boost::empty_value<Executor>
490 boost::weak_ptr<impl_type> wp_;
495 boost::weak_ptr<impl_type>&& wp)
496 : boost::empty_value<Executor>(
497 boost::empty_init_t{}, ex)
502 using executor_type = Executor;
505 get_executor() const noexcept
511 operator()(error_code ec)
514 if(ec == net::error::operation_aborted)
519 auto sp = wp_.lock();
526 case status::handshake:
531 // timeout was disabled
532 if(impl.timeout_opt.idle_timeout == none())
535 if( impl.timeout_opt.keep_alive_pings &&
536 impl.idle_counter < 1)
538 idle_ping_op<Executor>(sp, get_executor());
541 impl.timer.expires_after(
542 impl.timeout_opt.idle_timeout / 2);
543 impl.timer.async_wait(std::move(*this));
550 case status::closing:
563 //--------------------------------------------------------------------------
567 //--------------------------------------------------------------------------
569 template<class NextLayer, bool deflateSupported>
570 template<class Decorator>
572 stream<NextLayer, deflateSupported>::impl_type::
574 detail::sec_ws_key_type& key,
575 string_view host, string_view target,
576 Decorator const& decorator)
581 req.method(http::verb::get);
582 req.set(http::field::host, host);
583 req.set(http::field::upgrade, "websocket");
584 req.set(http::field::connection, "upgrade");
585 detail::make_sec_ws_key(key);
586 req.set(http::field::sec_websocket_key, key);
587 req.set(http::field::sec_websocket_version, "13");
588 this->build_request_pmd(req);
591 if(! req.count(http::field::user_agent))
592 req.set(http::field::user_agent,
593 BOOST_BEAST_VERSION_STRING);
597 // Called when the WebSocket Upgrade response is received
598 template<class NextLayer, bool deflateSupported>
600 stream<NextLayer, deflateSupported>::impl_type::
602 response_type const& res,
603 detail::sec_ws_key_type const& key,
611 if(res.result() != http::status::switching_protocols)
612 return err(error::upgrade_declined);
613 if(res.version() != 11)
614 return err(error::bad_http_version);
616 auto const it = res.find(http::field::connection);
618 return err(error::no_connection);
619 if(! http::token_list{it->value()}.exists("upgrade"))
620 return err(error::no_connection_upgrade);
623 auto const it = res.find(http::field::upgrade);
625 return err(error::no_upgrade);
626 if(! http::token_list{it->value()}.exists("websocket"))
627 return err(error::no_upgrade_websocket);
630 auto const it = res.find(
631 http::field::sec_websocket_accept);
633 return err(error::no_sec_accept);
634 detail::sec_ws_accept_type acc;
635 detail::make_sec_ws_accept(acc, key);
636 if(acc.compare(it->value()) != 0)
637 return err(error::bad_sec_accept);
641 this->on_response_pmd(res);
642 this->open(role_type::client);
645 //------------------------------------------------------------------------------
647 // Attempt to read a complete frame header.
648 // Returns `false` if more bytes are needed
649 template<class NextLayer, bool deflateSupported>
650 template<class DynamicBuffer>
652 stream<NextLayer, deflateSupported>::impl_type::
654 detail::frame_header& fh,
658 if(buffer_bytes(b.data()) < 2)
664 buffers_suffix<typename
665 DynamicBuffer::const_buffers_type> cb{
670 cb.consume(net::buffer_copy(
671 net::buffer(tmp), cb));
672 fh.len = tmp[1] & 0x7f;
675 case 126: need = 2; break;
676 case 127: need = 8; break;
680 fh.mask = (tmp[1] & 0x80) != 0;
683 if(buffer_bytes(cb) < need)
690 detail::opcode>(tmp[0] & 0x0f);
691 fh.fin = (tmp[0] & 0x80) != 0;
692 fh.rsv1 = (tmp[0] & 0x40) != 0;
693 fh.rsv2 = (tmp[0] & 0x20) != 0;
694 fh.rsv3 = (tmp[0] & 0x10) != 0;
698 case detail::opcode::binary:
699 case detail::opcode::text:
702 // new data frame when continuation expected
703 ec = error::bad_data_frame;
706 if(fh.rsv2 || fh.rsv3 ||
707 ! this->rd_deflated(fh.rsv1))
709 // reserved bits not cleared
710 ec = error::bad_reserved_bits;
715 case detail::opcode::cont:
718 // continuation without an active message
719 ec = error::bad_continuation;
722 if(fh.rsv1 || fh.rsv2 || fh.rsv3)
724 // reserved bits not cleared
725 ec = error::bad_reserved_bits;
731 if(detail::is_reserved(fh.op))
734 ec = error::bad_opcode;
739 // fragmented control message
740 ec = error::bad_control_fragment;
745 // invalid length for control message
746 ec = error::bad_control_size;
749 if(fh.rsv1 || fh.rsv2 || fh.rsv3)
751 // reserved bits not cleared
752 ec = error::bad_reserved_bits;
757 if(role == role_type::server && ! fh.mask)
759 // unmasked frame from client
760 ec = error::bad_unmasked_frame;
763 if(role == role_type::client && fh.mask)
765 // masked frame from server
766 ec = error::bad_masked_frame;
769 if(detail::is_control(fh.op) &&
770 buffer_bytes(cb) < need + fh.len)
772 // Make the entire control frame payload
773 // get read in before we return `true`
781 std::uint16_t len_be;
782 BOOST_ASSERT(buffer_bytes(cb) >= sizeof(len_be));
783 cb.consume(net::buffer_copy(
784 net::mutable_buffer(&len_be, sizeof(len_be)), cb));
785 fh.len = endian::big_to_native(len_be);
788 // length not canonical
789 ec = error::bad_size;
796 std::uint64_t len_be;
797 BOOST_ASSERT(buffer_bytes(cb) >= sizeof(len_be));
798 cb.consume(net::buffer_copy(
799 net::mutable_buffer(&len_be, sizeof(len_be)), cb));
800 fh.len = endian::big_to_native(len_be);
803 // length not canonical
804 ec = error::bad_size;
812 std::uint32_t key_le;
813 BOOST_ASSERT(buffer_bytes(cb) >= sizeof(key_le));
814 cb.consume(net::buffer_copy(
815 net::mutable_buffer(&key_le, sizeof(key_le)), cb));
816 fh.key = endian::little_to_native(key_le);
817 detail::prepare_key(rd_key, fh.key);
821 // initialize this otherwise operator== breaks
824 if(! detail::is_control(fh.op))
826 if(fh.op != detail::opcode::cont)
833 if(rd_size > (std::numeric_limits<
834 std::uint64_t>::max)() - fh.len)
836 // message size exceeds configured limit
837 ec = error::message_too_big;
841 if(! this->rd_deflated())
843 if(rd_msg_max && beast::detail::sum_exceeds(
844 rd_size, fh.len, rd_msg_max))
846 // message size exceeds configured limit
847 ec = error::message_too_big;
854 b.consume(b.size() - buffer_bytes(cb));
859 template<class NextLayer, bool deflateSupported>
860 template<class DynamicBuffer>
862 stream<NextLayer, deflateSupported>::impl_type::
863 write_ping(DynamicBuffer& db,
864 detail::opcode code, ping_data const& data)
866 detail::frame_header fh;
872 fh.len = data.size();
873 fh.mask = role == role_type::client;
875 fh.key = create_mask();
876 detail::write(db, fh);
879 detail::prepared_key key;
881 detail::prepare_key(key, fh.key);
882 auto mb = db.prepare(data.size());
885 data.data(), data.size()));
887 detail::mask_inplace(mb, key);
888 db.commit(data.size());
891 template<class NextLayer, bool deflateSupported>
892 template<class DynamicBuffer>
894 stream<NextLayer, deflateSupported>::impl_type::
895 write_close(DynamicBuffer& db, close_reason const& cr)
897 using namespace boost::endian;
898 detail::frame_header fh;
899 fh.op = detail::opcode::close;
904 fh.len = cr.code == close_code::none ?
905 0 : 2 + cr.reason.size();
906 if(role == role_type::client)
909 fh.key = create_mask();
915 detail::write(db, fh);
916 if(cr.code != close_code::none)
918 detail::prepared_key key;
920 detail::prepare_key(key, fh.key);
922 auto code_be = endian::native_to_big<std::uint16_t>(cr.code);
923 auto mb = db.prepare(2);
925 net::const_buffer(&code_be, sizeof(code_be)));
927 detail::mask_inplace(mb, key);
930 if(! cr.reason.empty())
932 auto mb = db.prepare(cr.reason.size());
935 cr.reason.data(), cr.reason.size()));
937 detail::mask_inplace(mb, key);
938 db.commit(cr.reason.size());