Imported Upstream version 1.72.0
[platform/upstream/boost.git] / boost / beast / websocket / impl / stream_impl.hpp
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/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>
39
40 namespace boost {
41 namespace beast {
42 namespace websocket {
43
44 template<
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>
50 {
51     NextLayer& stream() noexcept
52     {
53         return this->boost::empty_value<
54             NextLayer>::get();
55     }
56
57     boost::weak_ptr<impl_type>
58     weak_from_this()
59     {
60         return boost::static_pointer_cast<
61             impl_type>(this->detail::service::
62                 impl_type::shared_from_this());
63     }
64
65     boost::shared_ptr<impl_type>
66     shared_this()
67     {
68         return boost::static_pointer_cast<
69             impl_type>(this->detail::service::
70                 impl_type::shared_from_this());
71     }
72
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
76
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
84     static_buffer<
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
91
92     role_type               role            /* server or client */ = role_type::client;
93     status                  status_         /* state of the object */ = status::closed;
94
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;
103     std::unique_ptr<
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
108
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)
116
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;
122
123     detail::decorator       decorator_opt;  // Decorator for HTTP messages
124     timeout                 timeout_opt;    // Timeout/idle settings
125
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())
134     {
135         timeout_opt.handshake_timeout = none();
136         timeout_opt.idle_timeout = none();
137         timeout_opt.keep_alive_pings = false;
138     }
139
140     void
141     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
153     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
182     close()
183     {
184         timer.cancel();
185         wr_buf.reset();
186         this->close_pmd();
187     }
188
189     void
190     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
214     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
224     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
282     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
292     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
315     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
337     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
377     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
404     reset_idle()
405     {
406         idle_counter = 0;
407     }
408
409     // Maintain the expiration timer
410     template<class Executor>
411     void
412     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                 timer.async_wait(
424                     timeout_handler<Executor>(
425                         ex, this->weak_from_this()));
426             }
427             break;
428
429         case status::open:
430             if(timeout_opt.idle_timeout != none())
431             {
432                 idle_counter = 0;
433                 if(timeout_opt.keep_alive_pings)
434                     timer.expires_after(
435                         timeout_opt.idle_timeout / 2);
436                 else
437                     timer.expires_after(
438                         timeout_opt.idle_timeout);
439                 timer.async_wait(
440                     timeout_handler<Executor>(
441                         ex, this->weak_from_this()));
442             }
443             else
444             {
445                 timer.cancel();
446                 timer.expires_at(never());
447             }
448             break;
449
450         case status::closing:
451             if(timeout_opt.handshake_timeout != none())
452             {
453                 idle_counter = 0;
454                 timer.expires_after(
455                     timeout_opt.handshake_timeout);
456                 timer.async_wait(
457                     timeout_handler<Executor>(
458                         ex, this->weak_from_this()));
459             }
460             else
461             {
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());
467             }
468             break;
469
470         case status::failed:
471         case status::closed:
472             // this->close(); // Is this right?
473             timer.cancel();
474             timer.expires_at(never());
475             break;
476         }
477     }
478
479 private:
480     bool
481     is_timer_set() const
482     {
483         return timer.expiry() != never();
484     }
485
486     template<class Executor>
487     class timeout_handler
488         : boost::empty_value<Executor>
489     {
490         boost::weak_ptr<impl_type> wp_;
491
492     public:
493         timeout_handler(
494             Executor const& ex,
495             boost::weak_ptr<impl_type>&& wp)
496             : boost::empty_value<Executor>(
497                 boost::empty_init_t{}, ex)
498             , wp_(std::move(wp))
499         {
500         }
501
502         using executor_type = Executor;
503
504         executor_type
505         get_executor() const noexcept
506         {
507             return this->get();
508         }
509
510         void
511         operator()(error_code ec)
512         {
513             // timer canceled?
514             if(ec == net::error::operation_aborted)
515                 return;
516             BOOST_ASSERT(! ec);
517
518             // stream destroyed?
519             auto sp = wp_.lock();
520             if(! sp)
521                 return;
522             auto& impl = *sp;
523
524             switch(impl.status_)
525             {
526             case status::handshake:
527                 impl.time_out();
528                 return;
529
530             case status::open:
531                 // timeout was disabled
532                 if(impl.timeout_opt.idle_timeout == none())
533                     return;
534
535                 if( impl.timeout_opt.keep_alive_pings &&
536                     impl.idle_counter < 1)
537                 {
538                     idle_ping_op<Executor>(sp, get_executor());
539
540                     ++impl.idle_counter;
541                     impl.timer.expires_after(
542                         impl.timeout_opt.idle_timeout / 2);
543                     impl.timer.async_wait(std::move(*this));
544                     return;
545                 }
546
547                 impl.time_out();
548                 return;
549
550             case status::closing:
551                 impl.time_out();
552                 return;
553
554             case status::closed:
555             case status::failed:
556                 // nothing to do?
557                 return;
558             }
559         }
560     };
561 };
562
563 //--------------------------------------------------------------------------
564 //
565 // client
566 //
567 //--------------------------------------------------------------------------
568
569 template<class NextLayer, bool deflateSupported>
570 template<class Decorator>
571 request_type
572 stream<NextLayer, deflateSupported>::impl_type::
573 build_request(
574     detail::sec_ws_key_type& key,
575     string_view host, string_view target,
576     Decorator const& decorator)
577 {
578     request_type req;
579     req.target(target);
580     req.version(11);
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);
589     decorator_opt(req);
590     decorator(req);
591     if(! req.count(http::field::user_agent))
592         req.set(http::field::user_agent,
593             BOOST_BEAST_VERSION_STRING);
594     return req;
595 }
596
597 // Called when the WebSocket Upgrade response is received
598 template<class NextLayer, bool deflateSupported>
599 void
600 stream<NextLayer, deflateSupported>::impl_type::
601 on_response(
602     response_type const& res,
603     detail::sec_ws_key_type const& key,
604     error_code& ec)
605 {
606     auto const err =
607         [&](error e)
608         {
609             ec = e;
610         };
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);
615     {
616         auto const it = res.find(http::field::connection);
617         if(it == res.end())
618             return err(error::no_connection);
619         if(! http::token_list{it->value()}.exists("upgrade"))
620             return err(error::no_connection_upgrade);
621     }
622     {
623         auto const it = res.find(http::field::upgrade);
624         if(it == res.end())
625             return err(error::no_upgrade);
626         if(! http::token_list{it->value()}.exists("websocket"))
627             return err(error::no_upgrade_websocket);
628     }
629     {
630         auto const it = res.find(
631             http::field::sec_websocket_accept);
632         if(it == res.end())
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);
638     }
639
640     ec = {};
641     this->on_response_pmd(res);
642     this->open(role_type::client);
643 }
644
645 //------------------------------------------------------------------------------
646
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>
651 bool
652 stream<NextLayer, deflateSupported>::impl_type::
653 parse_fh(
654     detail::frame_header& fh,
655     DynamicBuffer& b,
656     error_code& ec)
657 {
658     if(buffer_bytes(b.data()) < 2)
659     {
660         // need more bytes
661         ec = {};
662         return false;
663     }
664     buffers_suffix<typename
665         DynamicBuffer::const_buffers_type> cb{
666             b.data()};
667     std::size_t need;
668     {
669         std::uint8_t tmp[2];
670         cb.consume(net::buffer_copy(
671             net::buffer(tmp), cb));
672         fh.len = tmp[1] & 0x7f;
673         switch(fh.len)
674         {
675             case 126: need = 2; break;
676             case 127: need = 8; break;
677             default:
678                 need = 0;
679         }
680         fh.mask = (tmp[1] & 0x80) != 0;
681         if(fh.mask)
682             need += 4;
683         if(buffer_bytes(cb) < need)
684         {
685             // need more bytes
686             ec = {};
687             return false;
688         }
689         fh.op   = static_cast<
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;
695     }
696     switch(fh.op)
697     {
698     case detail::opcode::binary:
699     case detail::opcode::text:
700         if(rd_cont)
701         {
702             // new data frame when continuation expected
703             ec = error::bad_data_frame;
704             return false;
705         }
706         if(fh.rsv2 || fh.rsv3 ||
707             ! this->rd_deflated(fh.rsv1))
708         {
709             // reserved bits not cleared
710             ec = error::bad_reserved_bits;
711             return false;
712         }
713         break;
714
715     case detail::opcode::cont:
716         if(! rd_cont)
717         {
718             // continuation without an active message
719             ec = error::bad_continuation;
720             return false;
721         }
722         if(fh.rsv1 || fh.rsv2 || fh.rsv3)
723         {
724             // reserved bits not cleared
725             ec = error::bad_reserved_bits;
726             return false;
727         }
728         break;
729
730     default:
731         if(detail::is_reserved(fh.op))
732         {
733             // reserved opcode
734             ec = error::bad_opcode;
735             return false;
736         }
737         if(! fh.fin)
738         {
739             // fragmented control message
740             ec = error::bad_control_fragment;
741             return false;
742         }
743         if(fh.len > 125)
744         {
745             // invalid length for control message
746             ec = error::bad_control_size;
747             return false;
748         }
749         if(fh.rsv1 || fh.rsv2 || fh.rsv3)
750         {
751             // reserved bits not cleared
752             ec = error::bad_reserved_bits;
753             return false;
754         }
755         break;
756     }
757     if(role == role_type::server && ! fh.mask)
758     {
759         // unmasked frame from client
760         ec = error::bad_unmasked_frame;
761         return false;
762     }
763     if(role == role_type::client && fh.mask)
764     {
765         // masked frame from server
766         ec = error::bad_masked_frame;
767         return false;
768     }
769     if(detail::is_control(fh.op) &&
770         buffer_bytes(cb) < need + fh.len)
771     {
772         // Make the entire control frame payload
773         // get read in before we return `true`
774         return false;
775     }
776     switch(fh.len)
777     {
778     case 126:
779     {
780
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);
786         if(fh.len < 126)
787         {
788             // length not canonical
789             ec = error::bad_size;
790             return false;
791         }
792         break;
793     }
794     case 127:
795     {
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);
801         if(fh.len < 65536)
802         {
803             // length not canonical
804             ec = error::bad_size;
805             return false;
806         }
807         break;
808     }
809     }
810     if(fh.mask)
811     {
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);
818     }
819     else
820     {
821         // initialize this otherwise operator== breaks
822         fh.key = 0;
823     }
824     if(! detail::is_control(fh.op))
825     {
826         if(fh.op != detail::opcode::cont)
827         {
828             rd_size = 0;
829             rd_op = fh.op;
830         }
831         else
832         {
833             if(rd_size > (std::numeric_limits<
834                 std::uint64_t>::max)() - fh.len)
835             {
836                 // message size exceeds configured limit
837                 ec = error::message_too_big;
838                 return false;
839             }
840         }
841         if(! this->rd_deflated())
842         {
843             if(rd_msg_max && beast::detail::sum_exceeds(
844                 rd_size, fh.len, rd_msg_max))
845             {
846                 // message size exceeds configured limit
847                 ec = error::message_too_big;
848                 return false;
849             }
850         }
851         rd_cont = ! fh.fin;
852         rd_remain = fh.len;
853     }
854     b.consume(b.size() - buffer_bytes(cb));
855     ec = {};
856     return true;
857 }
858
859 template<class NextLayer, bool deflateSupported>
860 template<class DynamicBuffer>
861 void
862 stream<NextLayer, deflateSupported>::impl_type::
863 write_ping(DynamicBuffer& db,
864     detail::opcode code, ping_data const& data)
865 {
866     detail::frame_header fh;
867     fh.op = code;
868     fh.fin = true;
869     fh.rsv1 = false;
870     fh.rsv2 = false;
871     fh.rsv3 = false;
872     fh.len = data.size();
873     fh.mask = role == role_type::client;
874     if(fh.mask)
875         fh.key = create_mask();
876     detail::write(db, fh);
877     if(data.empty())
878         return;
879     detail::prepared_key key;
880     if(fh.mask)
881         detail::prepare_key(key, fh.key);
882     auto mb = db.prepare(data.size());
883     net::buffer_copy(mb,
884         net::const_buffer(
885             data.data(), data.size()));
886     if(fh.mask)
887         detail::mask_inplace(mb, key);
888     db.commit(data.size());
889 }
890
891 template<class NextLayer, bool deflateSupported>
892 template<class DynamicBuffer>
893 void
894 stream<NextLayer, deflateSupported>::impl_type::
895 write_close(DynamicBuffer& db, close_reason const& cr)
896 {
897     using namespace boost::endian;
898     detail::frame_header fh;
899     fh.op = detail::opcode::close;
900     fh.fin = true;
901     fh.rsv1 = false;
902     fh.rsv2 = false;
903     fh.rsv3 = false;
904     fh.len = cr.code == close_code::none ?
905         0 : 2 + cr.reason.size();
906     if(role == role_type::client)
907     {
908         fh.mask = true;
909         fh.key = create_mask();
910     }
911     else
912     {
913         fh.mask = false;
914     }
915     detail::write(db, fh);
916     if(cr.code != close_code::none)
917     {
918         detail::prepared_key key;
919         if(fh.mask)
920             detail::prepare_key(key, fh.key);
921         {
922             auto code_be = endian::native_to_big<std::uint16_t>(cr.code);
923             auto mb = db.prepare(2);
924             net::buffer_copy(mb,
925                 net::const_buffer(&code_be, sizeof(code_be)));
926             if(fh.mask)
927                 detail::mask_inplace(mb, key);
928             db.commit(2);
929         }
930         if(! cr.reason.empty())
931         {
932             auto mb = db.prepare(cr.reason.size());
933             net::buffer_copy(mb,
934                 net::const_buffer(
935                     cr.reason.data(), cr.reason.size()));
936             if(fh.mask)
937                 detail::mask_inplace(mb, key);
938             db.commit(cr.reason.size());
939         }
940     }
941 }
942
943 } // websocket
944 } // beast
945 } // boost
946
947 #endif