summaryrefslogtreecommitdiff
path: root/boost/beast/websocket/impl/write.ipp
blob: d12f2f9e12e5a65047f1d869377337286a2efa36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_WEBSOCKET_IMPL_WRITE_IPP
#define BOOST_BEAST_WEBSOCKET_IMPL_WRITE_IPP

#include <boost/beast/core/bind_handler.hpp>
#include <boost/beast/core/buffers_cat.hpp>
#include <boost/beast/core/buffers_prefix.hpp>
#include <boost/beast/core/buffers_suffix.hpp>
#include <boost/beast/core/flat_static_buffer.hpp>
#include <boost/beast/core/type_traits.hpp>
#include <boost/beast/core/detail/clamp.hpp>
#include <boost/beast/core/detail/config.hpp>
#include <boost/beast/websocket/detail/frame.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/handler_continuation_hook.hpp>
#include <boost/asio/handler_invoke_hook.hpp>
#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#include <algorithm>
#include <memory>

namespace boost {
namespace beast {
namespace websocket {

namespace detail {

// Compress a buffer sequence
// Returns: `true` if more calls are needed
//
template<>
template<class ConstBufferSequence>
bool
stream_base<true>::
deflate(
    boost::asio::mutable_buffer& out,
    buffers_suffix<ConstBufferSequence>& cb,
    bool fin,
    std::size_t& total_in,
    error_code& ec)
{
    using boost::asio::buffer;
    BOOST_ASSERT(out.size() >= 6);
    auto& zo = this->pmd_->zo;
    zlib::z_params zs;
    zs.avail_in = 0;
    zs.next_in = nullptr;
    zs.avail_out = out.size();
    zs.next_out = out.data();
    for(auto in : beast::detail::buffers_range(cb))
    {
        zs.avail_in = in.size();
        if(zs.avail_in == 0)
            continue;
        zs.next_in = in.data();
        zo.write(zs, zlib::Flush::none, ec);
        if(ec)
        {
            if(ec != zlib::error::need_buffers)
                return false;
            BOOST_ASSERT(zs.avail_out == 0);
            BOOST_ASSERT(zs.total_out == out.size());
            ec.assign(0, ec.category());
            break;
        }
        if(zs.avail_out == 0)
        {
            BOOST_ASSERT(zs.total_out == out.size());
            break;
        }
        BOOST_ASSERT(zs.avail_in == 0);
    }
    total_in = zs.total_in;
    cb.consume(zs.total_in);
    if(zs.avail_out > 0 && fin)
    {
        auto const remain = boost::asio::buffer_size(cb);
        if(remain == 0)
        {
            // Inspired by Mark Adler
            // https://github.com/madler/zlib/issues/149
            //
            // VFALCO We could do this flush twice depending
            //        on how much space is in the output.
            zo.write(zs, zlib::Flush::block, ec);
            BOOST_ASSERT(! ec || ec == zlib::error::need_buffers);
            if(ec == zlib::error::need_buffers)
                ec.assign(0, ec.category());
            if(ec)
                return false;
            if(zs.avail_out >= 6)
            {
                zo.write(zs, zlib::Flush::full, ec);
                BOOST_ASSERT(! ec);
                // remove flush marker
                zs.total_out -= 4;
                out = buffer(out.data(), zs.total_out);
                return false;
            }
        }
    }
    ec.assign(0, ec.category());
    out = buffer(out.data(), zs.total_out);
    return true;
}

template<>
inline
void
stream_base<true>::
do_context_takeover_write(role_type role)
{
    if((role == role_type::client &&
        this->pmd_config_.client_no_context_takeover) ||
       (role == role_type::server &&
        this->pmd_config_.server_no_context_takeover))
    {
        this->pmd_->zo.reset();
    }
}

} // detail

//------------------------------------------------------------------------------

template<class NextLayer, bool deflateSupported>
template<class Buffers, class Handler>
class stream<NextLayer, deflateSupported>::write_some_op
    : public boost::asio::coroutine
{
    Handler h_;
    stream<NextLayer, deflateSupported>& ws_;
    buffers_suffix<Buffers> cb_;
    detail::frame_header fh_;
    detail::prepared_key key_;
    std::size_t bytes_transferred_ = 0;
    std::size_t remain_;
    std::size_t in_;
    int how_;
    bool fin_;
    bool more_;
    bool cont_ = false;

public:
    static constexpr int id = 2; // for soft_mutex

    write_some_op(write_some_op&&) = default;
    write_some_op(write_some_op const&) = delete;

    template<class DeducedHandler>
    write_some_op(
        DeducedHandler&& h,
        stream<NextLayer, deflateSupported>& ws,
        bool fin,
        Buffers const& bs)
        : h_(std::forward<DeducedHandler>(h))
        , ws_(ws)
        , cb_(bs)
        , fin_(fin)
    {
    }

    using allocator_type =
        boost::asio::associated_allocator_t<Handler>;

    allocator_type
    get_allocator() const noexcept
    {
        return (boost::asio::get_associated_allocator)(h_);
    }

    using executor_type = boost::asio::associated_executor_t<
        Handler, decltype(std::declval<stream<NextLayer, deflateSupported>&>().get_executor())>;

    executor_type
    get_executor() const noexcept
    {
        return (boost::asio::get_associated_executor)(
            h_, ws_.get_executor());
    }

    Handler&
    handler()
    {
        return h_;
    }

    void operator()(
        error_code ec = {},
        std::size_t bytes_transferred = 0,
        bool cont = true);

    friend
    bool asio_handler_is_continuation(write_some_op* op)
    {
        using boost::asio::asio_handler_is_continuation;
        return op->cont_ || asio_handler_is_continuation(
            std::addressof(op->h_));
    }

    template<class Function>
    friend
    void asio_handler_invoke(Function&& f, write_some_op* op)
    {
        using boost::asio::asio_handler_invoke;
        asio_handler_invoke(
            f, std::addressof(op->h_));
    }
};

template<class NextLayer, bool deflateSupported>
template<class Buffers, class Handler>
void
stream<NextLayer, deflateSupported>::
write_some_op<Buffers, Handler>::
operator()(
    error_code ec,
    std::size_t bytes_transferred,
    bool cont)
{
    using beast::detail::clamp;
    using boost::asio::buffer;
    using boost::asio::buffer_copy;
    using boost::asio::buffer_size;
    using boost::asio::mutable_buffer;
    enum
    {
        do_nomask_nofrag,
        do_nomask_frag,
        do_mask_nofrag,
        do_mask_frag,
        do_deflate
    };
    std::size_t n;
    boost::asio::mutable_buffer b;
    cont_ = cont;
    BOOST_ASIO_CORO_REENTER(*this)
    {
        // Set up the outgoing frame header
        if(! ws_.wr_cont_)
        {
            ws_.begin_msg();
            fh_.rsv1 = ws_.wr_compress_;
        }
        else
        {
            fh_.rsv1 = false;
        }
        fh_.rsv2 = false;
        fh_.rsv3 = false;
        fh_.op = ws_.wr_cont_ ?
            detail::opcode::cont : ws_.wr_opcode_;
        fh_.mask =
            ws_.role_ == role_type::client;

        // Choose a write algorithm
        if(ws_.wr_compress_)
        {
            how_ = do_deflate;
        }
        else if(! fh_.mask)
        {
            if(! ws_.wr_frag_)
            {
                how_ = do_nomask_nofrag;
            }
            else
            {
                BOOST_ASSERT(ws_.wr_buf_size_ != 0);
                remain_ = buffer_size(cb_);
                if(remain_ > ws_.wr_buf_size_)
                    how_ = do_nomask_frag;
                else
                    how_ = do_nomask_nofrag;
            }
        }
        else
        {
            if(! ws_.wr_frag_)
            {
                how_ = do_mask_nofrag;
            }
            else
            {
                BOOST_ASSERT(ws_.wr_buf_size_ != 0);
                remain_ = buffer_size(cb_);
                if(remain_ > ws_.wr_buf_size_)
                    how_ = do_mask_frag;
                else
                    how_ = do_mask_nofrag;
            }
        }

        // Maybe suspend
        if(ws_.wr_block_.try_lock(this))
        {
            // Make sure the stream is open
            if(! ws_.check_open(ec))
                goto upcall;
        }
        else
        {
        do_suspend:
            // Suspend
            BOOST_ASIO_CORO_YIELD
            ws_.paused_wr_.emplace(std::move(*this));

            // Acquire the write block
            ws_.wr_block_.lock(this);

            // Resume
            BOOST_ASIO_CORO_YIELD
            boost::asio::post(
                ws_.get_executor(), std::move(*this));
            BOOST_ASSERT(ws_.wr_block_.is_locked(this));

            // Make sure the stream is open
            if(! ws_.check_open(ec))
                goto upcall;
        }

        //------------------------------------------------------------------

        if(how_ == do_nomask_nofrag)
        {
            fh_.fin = fin_;
            fh_.len = buffer_size(cb_);
            ws_.wr_fb_.reset();
            detail::write<flat_static_buffer_base>(
                ws_.wr_fb_, fh_);
            ws_.wr_cont_ = ! fin_;
            // Send frame
            BOOST_ASIO_CORO_YIELD
            boost::asio::async_write(ws_.stream_,
                buffers_cat(ws_.wr_fb_.data(), cb_),
                    std::move(*this));
            if(! ws_.check_ok(ec))
                goto upcall;
            bytes_transferred_ += clamp(fh_.len);
            goto upcall;
        }

        //------------------------------------------------------------------

        else if(how_ == do_nomask_frag)
        {
            for(;;)
            {
                n = clamp(remain_, ws_.wr_buf_size_);
                fh_.len = n;
                remain_ -= n;
                fh_.fin = fin_ ? remain_ == 0 : false;
                ws_.wr_fb_.reset();
                detail::write<flat_static_buffer_base>(
                    ws_.wr_fb_, fh_);
                ws_.wr_cont_ = ! fin_;
                // Send frame
                BOOST_ASIO_CORO_YIELD
                boost::asio::async_write(
                    ws_.stream_, buffers_cat(
                        ws_.wr_fb_.data(), buffers_prefix(
                            clamp(fh_.len), cb_)),
                                std::move(*this));
                if(! ws_.check_ok(ec))
                    goto upcall;
                n = clamp(fh_.len); // because yield
                bytes_transferred_ += n;
                if(remain_ == 0)
                    break;
                cb_.consume(n);
                fh_.op = detail::opcode::cont;
                // Allow outgoing control frames to
                // be sent in between message frames
                ws_.wr_block_.unlock(this);
                if( ws_.paused_close_.maybe_invoke() ||
                    ws_.paused_rd_.maybe_invoke() ||
                    ws_.paused_ping_.maybe_invoke())
                {
                    BOOST_ASSERT(ws_.wr_block_.is_locked());
                    goto do_suspend;
                }
                ws_.wr_block_.lock(this);
            }
            goto upcall;
        }

        //------------------------------------------------------------------

        else if(how_ == do_mask_nofrag)
        {
            remain_ = buffer_size(cb_);
            fh_.fin = fin_;
            fh_.len = remain_;
            fh_.key = ws_.wr_gen_();
            detail::prepare_key(key_, fh_.key);
            ws_.wr_fb_.reset();
            detail::write<flat_static_buffer_base>(
                ws_.wr_fb_, fh_);
            n = clamp(remain_, ws_.wr_buf_size_);
            buffer_copy(buffer(
                ws_.wr_buf_.get(), n), cb_);
            detail::mask_inplace(buffer(
                ws_.wr_buf_.get(), n), key_);
            remain_ -= n;
            ws_.wr_cont_ = ! fin_;
            // Send frame header and partial payload
            BOOST_ASIO_CORO_YIELD
            boost::asio::async_write(
                ws_.stream_, buffers_cat(ws_.wr_fb_.data(),
                    buffer(ws_.wr_buf_.get(), n)),
                        std::move(*this));
            if(! ws_.check_ok(ec))
                goto upcall;
            bytes_transferred_ +=
                bytes_transferred - ws_.wr_fb_.size();
            while(remain_ > 0)
            {
                cb_.consume(ws_.wr_buf_size_);
                n = clamp(remain_, ws_.wr_buf_size_);
                buffer_copy(buffer(
                    ws_.wr_buf_.get(), n), cb_);
                detail::mask_inplace(buffer(
                    ws_.wr_buf_.get(), n), key_);
                remain_ -= n;
                // Send partial payload
                BOOST_ASIO_CORO_YIELD
                boost::asio::async_write(ws_.stream_,
                    buffer(ws_.wr_buf_.get(), n),
                        std::move(*this));
                if(! ws_.check_ok(ec))
                    goto upcall;
                bytes_transferred_ += bytes_transferred;
            }
            goto upcall;
        }

        //------------------------------------------------------------------

        else if(how_ == do_mask_frag)
        {
            for(;;)
            {
                n = clamp(remain_, ws_.wr_buf_size_);
                remain_ -= n;
                fh_.len = n;
                fh_.key = ws_.wr_gen_();
                fh_.fin = fin_ ? remain_ == 0 : false;
                detail::prepare_key(key_, fh_.key);
                buffer_copy(buffer(
                    ws_.wr_buf_.get(), n), cb_);
                detail::mask_inplace(buffer(
                    ws_.wr_buf_.get(), n), key_);
                ws_.wr_fb_.reset();
                detail::write<flat_static_buffer_base>(
                    ws_.wr_fb_, fh_);
                ws_.wr_cont_ = ! fin_;
                // Send frame
                BOOST_ASIO_CORO_YIELD
                boost::asio::async_write(ws_.stream_,
                    buffers_cat(ws_.wr_fb_.data(),
                        buffer(ws_.wr_buf_.get(), n)),
                            std::move(*this));
                if(! ws_.check_ok(ec))
                    goto upcall;
                n = bytes_transferred - ws_.wr_fb_.size();
                bytes_transferred_ += n;
                if(remain_ == 0)
                    break;
                cb_.consume(n);
                fh_.op = detail::opcode::cont;
                // Allow outgoing control frames to
                // be sent in between message frames:
                ws_.wr_block_.unlock(this);
                if( ws_.paused_close_.maybe_invoke() ||
                    ws_.paused_rd_.maybe_invoke() ||
                    ws_.paused_ping_.maybe_invoke())
                {
                    BOOST_ASSERT(ws_.wr_block_.is_locked());
                    goto do_suspend;
                }
                ws_.wr_block_.lock(this);
            }
            goto upcall;
        }

        //------------------------------------------------------------------

        else if(how_ == do_deflate)
        {
            for(;;)
            {
                b = buffer(ws_.wr_buf_.get(),
                    ws_.wr_buf_size_);
                more_ = ws_.deflate(b, cb_, fin_, in_, ec);
                if(! ws_.check_ok(ec))
                    goto upcall;
                n = buffer_size(b);
                if(n == 0)
                {
                    // The input was consumed, but there
                    // is no output due to compression
                    // latency.
                    BOOST_ASSERT(! fin_);
                    BOOST_ASSERT(buffer_size(cb_) == 0);
                    goto upcall;
                }
                if(fh_.mask)
                {
                    fh_.key = ws_.wr_gen_();
                    detail::prepared_key key;
                    detail::prepare_key(key, fh_.key);
                    detail::mask_inplace(b, key);
                }
                fh_.fin = ! more_;
                fh_.len = n;
                ws_.wr_fb_.reset();
                detail::write<
                    flat_static_buffer_base>(ws_.wr_fb_, fh_);
                ws_.wr_cont_ = ! fin_;
                // Send frame
                BOOST_ASIO_CORO_YIELD
                boost::asio::async_write(ws_.stream_,
                    buffers_cat(ws_.wr_fb_.data(), b),
                        std::move(*this));
                if(! ws_.check_ok(ec))
                    goto upcall;
                bytes_transferred_ += in_;
                if(more_)
                {
                    fh_.op = detail::opcode::cont;
                    fh_.rsv1 = false;
                    // Allow outgoing control frames to
                    // be sent in between message frames:
                    ws_.wr_block_.unlock(this);
                    if( ws_.paused_close_.maybe_invoke() ||
                        ws_.paused_rd_.maybe_invoke() ||
                        ws_.paused_ping_.maybe_invoke())
                    {
                        BOOST_ASSERT(ws_.wr_block_.is_locked());
                        goto do_suspend;
                    }
                    ws_.wr_block_.lock(this);
                }
                else
                {
                    if(fh_.fin)
                        ws_.do_context_takeover_write(ws_.role_);
                    goto upcall;
                }
            }
        }

    //--------------------------------------------------------------------------

    upcall:
        ws_.wr_block_.unlock(this);
        ws_.paused_close_.maybe_invoke() ||
            ws_.paused_rd_.maybe_invoke() ||
            ws_.paused_ping_.maybe_invoke();
        if(! cont_)
            return boost::asio::post(
                ws_.stream_.get_executor(),
                bind_handler(std::move(h_), ec, bytes_transferred_));
        h_(ec, bytes_transferred_);
    }
}

//------------------------------------------------------------------------------

template<class NextLayer, bool deflateSupported>
template<class ConstBufferSequence>
std::size_t
stream<NextLayer, deflateSupported>::
write_some(bool fin, ConstBufferSequence const& buffers)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(boost::asio::is_const_buffer_sequence<
        ConstBufferSequence>::value,
            "ConstBufferSequence requirements not met");
    error_code ec;
    auto const bytes_transferred =
        write_some(fin, buffers, ec);
    if(ec)
        BOOST_THROW_EXCEPTION(system_error{ec});
    return bytes_transferred;
}

template<class NextLayer, bool deflateSupported>
template<class ConstBufferSequence>
std::size_t
stream<NextLayer, deflateSupported>::
write_some(bool fin,
    ConstBufferSequence const& buffers, error_code& ec)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(boost::asio::is_const_buffer_sequence<
        ConstBufferSequence>::value,
            "ConstBufferSequence requirements not met");
    using beast::detail::clamp;
    using boost::asio::buffer;
    using boost::asio::buffer_copy;
    using boost::asio::buffer_size;
    std::size_t bytes_transferred = 0;
    ec.assign(0, ec.category());
    // Make sure the stream is open
    if(! check_open(ec))
        return bytes_transferred;
    detail::frame_header fh;
    if(! wr_cont_)
    {
        begin_msg();
        fh.rsv1 = wr_compress_;
    }
    else
    {
        fh.rsv1 = false;
    }
    fh.rsv2 = false;
    fh.rsv3 = false;
    fh.op = wr_cont_ ?
        detail::opcode::cont : wr_opcode_;
    fh.mask = role_ == role_type::client;
    auto remain = buffer_size(buffers);
    if(wr_compress_)
    {
        buffers_suffix<
            ConstBufferSequence> cb{buffers};
        for(;;)
        {
            auto b = buffer(
                wr_buf_.get(), wr_buf_size_);
            auto const more = this->deflate(
                b, cb, fin, bytes_transferred, ec);
            if(! check_ok(ec))
                return bytes_transferred;
            auto const n = buffer_size(b);
            if(n == 0)
            {
                // The input was consumed, but there
                // is no output due to compression
                // latency.
                BOOST_ASSERT(! fin);
                BOOST_ASSERT(buffer_size(cb) == 0);
                fh.fin = false;
                break;
            }
            if(fh.mask)
            {
                fh.key = wr_gen_();
                detail::prepared_key key;
                detail::prepare_key(key, fh.key);
                detail::mask_inplace(b, key);
            }
            fh.fin = ! more;
            fh.len = n;
            detail::fh_buffer fh_buf;
            detail::write<
                flat_static_buffer_base>(fh_buf, fh);
            wr_cont_ = ! fin;
            boost::asio::write(stream_,
                buffers_cat(fh_buf.data(), b), ec);
            if(! check_ok(ec))
                return bytes_transferred;
            if(! more)
                break;
            fh.op = detail::opcode::cont;
            fh.rsv1 = false;
        }
        if(fh.fin)
            this->do_context_takeover_write(role_);
    }
    else if(! fh.mask)
    {
        if(! wr_frag_)
        {
            // no mask, no autofrag
            fh.fin = fin;
            fh.len = remain;
            detail::fh_buffer fh_buf;
            detail::write<
                flat_static_buffer_base>(fh_buf, fh);
            wr_cont_ = ! fin;
            boost::asio::write(stream_,
                buffers_cat(fh_buf.data(), buffers), ec);
            if(! check_ok(ec))
                return bytes_transferred;
            bytes_transferred += remain;
        }
        else
        {
            // no mask, autofrag
            BOOST_ASSERT(wr_buf_size_ != 0);
            buffers_suffix<
                ConstBufferSequence> cb{buffers};
            for(;;)
            {
                auto const n = clamp(remain, wr_buf_size_);
                remain -= n;
                fh.len = n;
                fh.fin = fin ? remain == 0 : false;
                detail::fh_buffer fh_buf;
                detail::write<
                    flat_static_buffer_base>(fh_buf, fh);
                wr_cont_ = ! fin;
                boost::asio::write(stream_,
                    buffers_cat(fh_buf.data(),
                        buffers_prefix(n, cb)), ec);
                if(! check_ok(ec))
                    return bytes_transferred;
                bytes_transferred += n;
                if(remain == 0)
                    break;
                fh.op = detail::opcode::cont;
                cb.consume(n);
            }
        }
    }
    else if(! wr_frag_)
    {
        // mask, no autofrag
        fh.fin = fin;
        fh.len = remain;
        fh.key = wr_gen_();
        detail::prepared_key key;
        detail::prepare_key(key, fh.key);
        detail::fh_buffer fh_buf;
        detail::write<
            flat_static_buffer_base>(fh_buf, fh);
        buffers_suffix<
            ConstBufferSequence> cb{buffers};
        {
            auto const n = clamp(remain, wr_buf_size_);
            auto const b = buffer(wr_buf_.get(), n);
            buffer_copy(b, cb);
            cb.consume(n);
            remain -= n;
            detail::mask_inplace(b, key);
            wr_cont_ = ! fin;
            boost::asio::write(stream_,
                buffers_cat(fh_buf.data(), b), ec);
            if(! check_ok(ec))
                return bytes_transferred;
            bytes_transferred += n;
        }
        while(remain > 0)
        {
            auto const n = clamp(remain, wr_buf_size_);
            auto const b = buffer(wr_buf_.get(), n);
            buffer_copy(b, cb);
            cb.consume(n);
            remain -= n;
            detail::mask_inplace(b, key);
            boost::asio::write(stream_, b, ec);
            if(! check_ok(ec))
                return bytes_transferred;
            bytes_transferred += n;
        }
    }
    else
    {
        // mask, autofrag
        BOOST_ASSERT(wr_buf_size_ != 0);
        buffers_suffix<
            ConstBufferSequence> cb{buffers};
        for(;;)
        {
            fh.key = wr_gen_();
            detail::prepared_key key;
            detail::prepare_key(key, fh.key);
            auto const n = clamp(remain, wr_buf_size_);
            auto const b = buffer(wr_buf_.get(), n);
            buffer_copy(b, cb);
            detail::mask_inplace(b, key);
            fh.len = n;
            remain -= n;
            fh.fin = fin ? remain == 0 : false;
            wr_cont_ = ! fh.fin;
            detail::fh_buffer fh_buf;
            detail::write<
                flat_static_buffer_base>(fh_buf, fh);
            boost::asio::write(stream_,
                buffers_cat(fh_buf.data(), b), ec);
            if(! check_ok(ec))
                return bytes_transferred;
            bytes_transferred += n;
            if(remain == 0)
                break;
            fh.op = detail::opcode::cont;
            cb.consume(n);
        }
    }
    return bytes_transferred;
}

template<class NextLayer, bool deflateSupported>
template<class ConstBufferSequence, class WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
    WriteHandler, void(error_code, std::size_t))
stream<NextLayer, deflateSupported>::
async_write_some(bool fin,
    ConstBufferSequence const& bs, WriteHandler&& handler)
{
    static_assert(is_async_stream<next_layer_type>::value,
        "AsyncStream requirements not met");
    static_assert(boost::asio::is_const_buffer_sequence<
        ConstBufferSequence>::value,
            "ConstBufferSequence requirements not met");
    BOOST_BEAST_HANDLER_INIT(
        WriteHandler, void(error_code, std::size_t));
    write_some_op<ConstBufferSequence, BOOST_ASIO_HANDLER_TYPE(
        WriteHandler, void(error_code, std::size_t))>{
            std::move(init.completion_handler), *this, fin, bs}(
                {}, 0, false);
    return init.result.get();
}

//------------------------------------------------------------------------------

template<class NextLayer, bool deflateSupported>
template<class ConstBufferSequence>
std::size_t
stream<NextLayer, deflateSupported>::
write(ConstBufferSequence const& buffers)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(boost::asio::is_const_buffer_sequence<
        ConstBufferSequence>::value,
            "ConstBufferSequence requirements not met");
    error_code ec;
    auto const bytes_transferred = write(buffers, ec);
    if(ec)
        BOOST_THROW_EXCEPTION(system_error{ec});
    return bytes_transferred;
}

template<class NextLayer, bool deflateSupported>
template<class ConstBufferSequence>
std::size_t
stream<NextLayer, deflateSupported>::
write(ConstBufferSequence const& buffers, error_code& ec)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(boost::asio::is_const_buffer_sequence<
        ConstBufferSequence>::value,
            "ConstBufferSequence requirements not met");
    return write_some(true, buffers, ec);
}

template<class NextLayer, bool deflateSupported>
template<class ConstBufferSequence, class WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
    WriteHandler, void(error_code, std::size_t))
stream<NextLayer, deflateSupported>::
async_write(
    ConstBufferSequence const& bs, WriteHandler&& handler)
{
    static_assert(is_async_stream<next_layer_type>::value,
        "AsyncStream requirements not met");
    static_assert(boost::asio::is_const_buffer_sequence<
        ConstBufferSequence>::value,
            "ConstBufferSequence requirements not met");
    BOOST_BEAST_HANDLER_INIT(
        WriteHandler, void(error_code, std::size_t));
    write_some_op<ConstBufferSequence, BOOST_ASIO_HANDLER_TYPE(
        WriteHandler, void(error_code, std::size_t))>{
            std::move(init.completion_handler), *this, true, bs}(
                {}, 0, false);
    return init.result.get();
}

} // websocket
} // beast
} // boost

#endif