aboutsummaryrefslogtreecommitdiffstats
path: root/websocketpp/extensions/permessage_deflate/enabled.hpp
blob: 1581f14cb4b019cbafaaa480794948407ebde016 (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
/*
 * Copyright (c) 2015, Peter Thorson. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the WebSocket++ Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#ifndef WEBSOCKETPP_PROCESSOR_EXTENSION_PERMESSAGEDEFLATE_HPP
#define WEBSOCKETPP_PROCESSOR_EXTENSION_PERMESSAGEDEFLATE_HPP


#include <websocketpp/common/cpp11.hpp>
#include <websocketpp/common/memory.hpp>
#include <websocketpp/common/platforms.hpp>
#include <websocketpp/common/system_error.hpp>
#include <websocketpp/error.hpp>

#include <websocketpp/extensions/extension.hpp>

#include "zlib.h"

#include <algorithm>
#include <string>
#include <vector>

namespace websocketpp {
namespace extensions {

/// Implementation of the draft permessage-deflate WebSocket extension
/**
 * ### permessage-deflate interface
 *
 * **init**\n
 * `lib::error_code init(bool is_server)`\n
 * Performs initialization
 *
 * **is_implimented**\n
 * `bool is_implimented()`\n
 * Returns whether or not the object impliments the extension or not
 *
 * **is_enabled**\n
 * `bool is_enabled()`\n
 * Returns whether or not the extension was negotiated for the current
 * connection
 *
 * **generate_offer**\n
 * `std::string generate_offer() const`\n
 * Create an extension offer string based on local policy
 *
 * **validate_response**\n
 * `lib::error_code validate_response(http::attribute_list const & response)`\n
 * Negotiate the parameters of extension use
 *
 * **negotiate**\n
 * `err_str_pair negotiate(http::attribute_list const & attributes)`\n
 * Negotiate the parameters of extension use
 *
 * **compress**\n
 * `lib::error_code compress(std::string const & in, std::string & out)`\n
 * Compress the bytes in `in` and append them to `out`
 *
 * **decompress**\n
 * `lib::error_code decompress(uint8_t const * buf, size_t len, std::string &
 * out)`\n
 * Decompress `len` bytes from `buf` and append them to string `out`
 */
namespace permessage_deflate {

/// Permessage deflate error values
namespace error {
enum value {
    /// Catch all
    general = 1,

    /// Invalid extension attributes
    invalid_attributes,

    /// Invalid extension attribute value
    invalid_attribute_value,

    /// Invalid megotiation mode
    invalid_mode,

    /// Unsupported extension attributes
    unsupported_attributes,

    /// Invalid value for max_window_bits
    invalid_max_window_bits,

    /// ZLib Error
    zlib_error,

    /// Uninitialized
    uninitialized,
};

/// Permessage-deflate error category
class category : public lib::error_category {
public:
    category() {}

    char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {
        return "websocketpp.extension.permessage-deflate";
    }

    std::string message(int value) const {
        switch(value) {
            case general:
                return "Generic permessage-compress error";
            case invalid_attributes:
                return "Invalid extension attributes";
            case invalid_attribute_value:
                return "Invalid extension attribute value";
            case invalid_mode:
                return "Invalid permessage-deflate negotiation mode";
            case unsupported_attributes:
                return "Unsupported extension attributes";
            case invalid_max_window_bits:
                return "Invalid value for max_window_bits";
            case zlib_error:
                return "A zlib function returned an error";
            case uninitialized:
                return "Deflate extension must be initialized before use";
            default:
                return "Unknown permessage-compress error";
        }
    }
};

/// Get a reference to a static copy of the permessage-deflate error category
inline lib::error_category const & get_category() {
    static category instance;
    return instance;
}

/// Create an error code in the permessage-deflate category
inline lib::error_code make_error_code(error::value e) {
    return lib::error_code(static_cast<int>(e), get_category());
}

} // namespace error
} // namespace permessage_deflate
} // namespace extensions
} // namespace websocketpp

_WEBSOCKETPP_ERROR_CODE_ENUM_NS_START_
template<> struct is_error_code_enum
    <websocketpp::extensions::permessage_deflate::error::value>
{
    static bool const value = true;
};
_WEBSOCKETPP_ERROR_CODE_ENUM_NS_END_
namespace websocketpp {
namespace extensions {
namespace permessage_deflate {

/// Default value for server_max_window_bits as defined by draft 17
static uint8_t const default_server_max_window_bits = 15;
/// Minimum value for server_max_window_bits as defined by draft 17
static uint8_t const min_server_max_window_bits = 8;
/// Maximum value for server_max_window_bits as defined by draft 17
static uint8_t const max_server_max_window_bits = 15;

/// Default value for client_max_window_bits as defined by draft 17
static uint8_t const default_client_max_window_bits = 15;
/// Minimum value for client_max_window_bits as defined by draft 17
static uint8_t const min_client_max_window_bits = 8;
/// Maximum value for client_max_window_bits as defined by draft 17
static uint8_t const max_client_max_window_bits = 15;

namespace mode {
enum value {
    /// Accept any value the remote endpoint offers
    accept = 1,
    /// Decline any value the remote endpoint offers. Insist on defaults.
    decline,
    /// Use the largest value common to both offers
    largest,
    /// Use the smallest value common to both offers
    smallest
};
} // namespace mode

template <typename config>
class enabled {
public:
    enabled()
      : m_enabled(false)
      , m_server_no_context_takeover(false)
      , m_client_no_context_takeover(false)
      , m_server_max_window_bits(15)
      , m_client_max_window_bits(15)
      , m_server_max_window_bits_mode(mode::accept)
      , m_client_max_window_bits_mode(mode::accept)
      , m_initialized(false)
      , m_compress_buffer_size(16384)
    {
        m_dstate.zalloc = Z_NULL;
        m_dstate.zfree = Z_NULL;
        m_dstate.opaque = Z_NULL;

        m_istate.zalloc = Z_NULL;
        m_istate.zfree = Z_NULL;
        m_istate.opaque = Z_NULL;
        m_istate.avail_in = 0;
        m_istate.next_in = Z_NULL;
    }

    ~enabled() {
        if (!m_initialized) {
            return;
        }

        int ret = deflateEnd(&m_dstate);

        if (ret != Z_OK) {
            //std::cout << "error cleaning up zlib compression state"
            //          << std::endl;
        }

        ret = inflateEnd(&m_istate);

        if (ret != Z_OK) {
            //std::cout << "error cleaning up zlib decompression state"
            //          << std::endl;
        }
    }

    /// Initialize zlib state
    /**
     * Note: this should be called *after* the negotiation methods. It will use
     * information from the negotiation to determine how to initialize the zlib
     * data structures.
     *
     * @todo memory level, strategy, etc are hardcoded
     *
     * @param is_server True to initialize as a server, false for a client.
     * @return A code representing the error that occurred, if any
     */
    lib::error_code init(bool is_server) {
        uint8_t deflate_bits;
        uint8_t inflate_bits;

        if (is_server) {
            deflate_bits = m_server_max_window_bits;
            inflate_bits = m_client_max_window_bits;
        } else {
            deflate_bits = m_client_max_window_bits;
            inflate_bits = m_server_max_window_bits;
        }

        int ret = deflateInit2(
            &m_dstate,
            Z_DEFAULT_COMPRESSION,
            Z_DEFLATED,
            -1*deflate_bits,
            4, // memory level 1-9
            Z_DEFAULT_STRATEGY
        );

        if (ret != Z_OK) {
            return make_error_code(error::zlib_error);
        }

        ret = inflateInit2(
            &m_istate,
            -1*inflate_bits
        );

        if (ret != Z_OK) {
            return make_error_code(error::zlib_error);
        }

        m_compress_buffer.reset(new unsigned char[m_compress_buffer_size]);
        if ((m_server_no_context_takeover && is_server) ||
            (m_client_no_context_takeover && !is_server))
        {
            m_flush = Z_FULL_FLUSH;
        } else {
            m_flush = Z_SYNC_FLUSH;
        }
        m_initialized = true;
        return lib::error_code();
    }

    /// Test if this object implements the permessage-deflate specification
    /**
     * Because this object does implieent it, it will always return true.
     *
     * @return Whether or not this object implements permessage-deflate
     */
    bool is_implemented() const {
        return true;
    }

    /// Test if the extension was negotiated for this connection
    /**
     * Retrieves whether or not this extension is in use based on the initial
     * handshake extension negotiations.
     *
     * @return Whether or not the extension is in use
     */
    bool is_enabled() const {
        return m_enabled;
    }

    /// Reset server's outgoing LZ77 sliding window for each new message
    /**
     * Enabling this setting will cause the server's compressor to reset the
     * compression state (the LZ77 sliding window) for every message. This
     * means that the compressor will not look back to patterns in previous
     * messages to improve compression. This will reduce the compression
     * efficiency for large messages somewhat and small messages drastically.
     *
     * This option may reduce server compressor memory usage and client
     * decompressor memory usage.
     * @todo Document to what extent memory usage will be reduced
     *
     * For clients, this option is dependent on server support. Enabling it
     * via this method does not guarantee that it will be successfully
     * negotiated, only that it will be requested.
     *
     * For servers, no client support is required. Enabling this option on a
     * server will result in its use. The server will signal to clients that
     * the option will be in use so they can optimize resource usage if they
     * are able.
     */
    void enable_server_no_context_takeover() {
        m_server_no_context_takeover = true;
    }

    /// Reset client's outgoing LZ77 sliding window for each new message
    /**
     * Enabling this setting will cause the client's compressor to reset the
     * compression state (the LZ77 sliding window) for every message. This
     * means that the compressor will not look back to patterns in previous
     * messages to improve compression. This will reduce the compression
     * efficiency for large messages somewhat and small messages drastically.
     *
     * This option may reduce client compressor memory usage and server
     * decompressor memory usage.
     * @todo Document to what extent memory usage will be reduced
     *
     * This option is supported by all compliant clients and servers. Enabling
     * it via either endpoint should be sufficient to ensure it is used.
     */
    void enable_client_no_context_takeover() {
        m_client_no_context_takeover = true;
    }

    /// Limit server LZ77 sliding window size
    /**
     * The bits setting is the base 2 logarithm of the maximum window size that
     * the server must use to compress outgoing messages. The permitted range
     * is 8 to 15 inclusive. 8 represents a 256 byte window and 15 a 32KiB
     * window. The default setting is 15.
     *
     * Mode Options:
     * - accept: Accept whatever the remote endpoint offers.
     * - decline: Decline any offers to deviate from the defaults
     * - largest: Accept largest window size acceptable to both endpoints
     * - smallest: Accept smallest window size acceptiable to both endpoints
     *
     * This setting is dependent on server support. A client requesting this
     * setting may be rejected by the server or have the exact value used
     * adjusted by the server. A server may unilaterally set this value without
     * client support.
     *
     * @param bits The size to request for the outgoing window size
     * @param mode The mode to use for negotiating this parameter
     * @return A status code
     */
    lib::error_code set_server_max_window_bits(uint8_t bits, mode::value mode) {
        if (bits < min_server_max_window_bits || bits > max_server_max_window_bits) {
            return error::make_error_code(error::invalid_max_window_bits);
        }
        m_server_max_window_bits = bits;
        m_server_max_window_bits_mode = mode;

        return lib::error_code();
    }

    /// Limit client LZ77 sliding window size
    /**
     * The bits setting is the base 2 logarithm of the window size that the
     * client must use to compress outgoing messages. The permitted range is 8
     * to 15 inclusive. 8 represents a 256 byte window and 15 a 32KiB window.
     * The default setting is 15.
     *
     * Mode Options:
     * - accept: Accept whatever the remote endpoint offers.
     * - decline: Decline any offers to deviate from the defaults
     * - largest: Accept largest window size acceptable to both endpoints
     * - smallest: Accept smallest window size acceptiable to both endpoints
     *
     * This setting is dependent on client support. A client may limit its own
     * outgoing window size unilaterally. A server may only limit the client's
     * window size if the remote client supports that feature.
     *
     * @param bits The size to request for the outgoing window size
     * @param mode The mode to use for negotiating this parameter
     * @return A status code
     */
    lib::error_code set_client_max_window_bits(uint8_t bits, mode::value mode) {
        if (bits < min_client_max_window_bits || bits > max_client_max_window_bits) {
            return error::make_error_code(error::invalid_max_window_bits);
        }
        m_client_max_window_bits = bits;
        m_client_max_window_bits_mode = mode;

        return lib::error_code();
    }

    /// Generate extension offer
    /**
     * Creates an offer string to include in the Sec-WebSocket-Extensions
     * header of outgoing client requests.
     *
     * @return A WebSocket extension offer string for this extension
     */
    std::string generate_offer() const {
        // TODO: this should be dynamically generated based on user settings
        return "permessage-deflate; client_no_context_takeover; client_max_window_bits";
    }

    /// Validate extension response
    /**
     * Confirm that the server has negotiated settings compatible with our
     * original offer and apply those settings to the extension state.
     *
     * @param response The server response attribute list to validate
     * @return Validation error or 0 on success
     */
    lib::error_code validate_offer(http::attribute_list const &) {
        return lib::error_code();
    }

    /// Negotiate extension
    /**
     * Confirm that the client's extension negotiation offer has settings
     * compatible with local policy. If so, generate a reply and apply those
     * settings to the extension state.
     *
     * @param offer Attribute from client's offer
     * @return Status code and value to return to remote endpoint
     */
    err_str_pair negotiate(http::attribute_list const & offer) {
        err_str_pair ret;

        http::attribute_list::const_iterator it;
        for (it = offer.begin(); it != offer.end(); ++it) {
            if (it->first == "server_no_context_takeover") {
                negotiate_server_no_context_takeover(it->second,ret.first);
            } else if (it->first == "client_no_context_takeover") {
                negotiate_client_no_context_takeover(it->second,ret.first);
            } else if (it->first == "server_max_window_bits") {
                negotiate_server_max_window_bits(it->second,ret.first);
            } else if (it->first == "client_max_window_bits") {
                negotiate_client_max_window_bits(it->second,ret.first);
            } else {
                ret.first = make_error_code(error::invalid_attributes);
            }

            if (ret.first) {
                break;
            }
        }

        if (ret.first == lib::error_code()) {
            m_enabled = true;
            ret.second = generate_response();
        }

        return ret;
    }

    /// Compress bytes
    /**
     * @todo: avail_in/out is 32 bit, need to fix for cases of >32 bit frames
     * on 64 bit machines.
     *
     * @param [in] in String to compress
     * @param [out] out String to append compressed bytes to
     * @return Error or status code
     */
    lib::error_code compress(std::string const & in, std::string & out) {
        if (!m_initialized) {
            return make_error_code(error::uninitialized);
        }

        size_t output;

        if (in.empty()) {
            uint8_t buf[6] = {0x02, 0x00, 0x00, 0x00, 0xff, 0xff};
            out.append((char *)(buf),6);
            return lib::error_code();
        }

        m_dstate.avail_in = in.size();
        m_dstate.next_in = (unsigned char *)(const_cast<char *>(in.data()));

        do {
            // Output to local buffer
            m_dstate.avail_out = m_compress_buffer_size;
            m_dstate.next_out = m_compress_buffer.get();

            deflate(&m_dstate, m_flush);

            output = m_compress_buffer_size - m_dstate.avail_out;

            out.append((char *)(m_compress_buffer.get()),output);
        } while (m_dstate.avail_out == 0);

        return lib::error_code();
    }

    /// Decompress bytes
    /**
     * @param buf Byte buffer to decompress
     * @param len Length of buf
     * @param out String to append decompressed bytes to
     * @return Error or status code
     */
    lib::error_code decompress(uint8_t const * buf, size_t len, std::string &
        out)
    {
        if (!m_initialized) {
            return make_error_code(error::uninitialized);
        }

        int ret;

        m_istate.avail_in = len;
        m_istate.next_in = const_cast<unsigned char *>(buf);

        do {
            m_istate.avail_out = m_compress_buffer_size;
            m_istate.next_out = m_compress_buffer.get();

            ret = inflate(&m_istate, Z_SYNC_FLUSH);

            if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) {
                return make_error_code(error::zlib_error);
            }

            out.append(
                reinterpret_cast<char *>(m_compress_buffer.get()),
                m_compress_buffer_size - m_istate.avail_out
            );
        } while (m_istate.avail_out == 0);

        return lib::error_code();
    }
private:
    /// Generate negotiation response
    /**
     * @return Generate extension negotiation reponse string to send to client
     */
    std::string generate_response() {
        std::string ret = "permessage-deflate";

        if (m_server_no_context_takeover) {
            ret += "; server_no_context_takeover";
        }

        if (m_client_no_context_takeover) {
            ret += "; client_no_context_takeover";
        }

        if (m_server_max_window_bits < default_server_max_window_bits) {
            std::stringstream s;
            s << int(m_server_max_window_bits);
            ret += "; server_max_window_bits="+s.str();
        }

        if (m_client_max_window_bits < default_client_max_window_bits) {
            std::stringstream s;
            s << int(m_client_max_window_bits);
            ret += "; client_max_window_bits="+s.str();
        }

        return ret;
    }

    /// Negotiate server_no_context_takeover attribute
    /**
     * @param [in] value The value of the attribute from the offer
     * @param [out] ec A reference to the error code to return errors via
     */
    void negotiate_server_no_context_takeover(std::string const & value,
        lib::error_code & ec)
    {
        if (!value.empty()) {
            ec = make_error_code(error::invalid_attribute_value);
            return;
        }

        m_server_no_context_takeover = true;
    }

    /// Negotiate client_no_context_takeover attribute
    /**
     * @param [in] value The value of the attribute from the offer
     * @param [out] ec A reference to the error code to return errors via
     */
    void negotiate_client_no_context_takeover(std::string const & value,
        lib::error_code & ec)
    {
        if (!value.empty()) {
            ec = make_error_code(error::invalid_attribute_value);
            return;
        }

        m_client_no_context_takeover = true;
    }

    /// Negotiate server_max_window_bits attribute
    /**
     * When this method starts, m_server_max_window_bits will contain the server's
     * preferred value and m_server_max_window_bits_mode will contain the mode the
     * server wants to use to for negotiation. `value` contains the value the
     * client requested that we use.
     *
     * options:
     * - decline (refuse to use the attribute)
     * - accept (use whatever the client says)
     * - largest (use largest possible value)
     * - smallest (use smallest possible value)
     *
     * @param [in] value The value of the attribute from the offer
     * @param [out] ec A reference to the error code to return errors via
     */
    void negotiate_server_max_window_bits(std::string const & value,
        lib::error_code & ec)
    {
        uint8_t bits = uint8_t(atoi(value.c_str()));

        if (bits < min_server_max_window_bits || bits > max_server_max_window_bits) {
            ec = make_error_code(error::invalid_attribute_value);
            m_server_max_window_bits = default_server_max_window_bits;
            return;
        }

        switch (m_server_max_window_bits_mode) {
            case mode::decline:
                m_server_max_window_bits = default_server_max_window_bits;
                break;
            case mode::accept:
                m_server_max_window_bits = bits;
                break;
            case mode::largest:
                m_server_max_window_bits = std::min(bits,m_server_max_window_bits);
                break;
            case mode::smallest:
                m_server_max_window_bits = min_server_max_window_bits;
                break;
            default:
                ec = make_error_code(error::invalid_mode);
                m_server_max_window_bits = default_server_max_window_bits;
        }
    }

    /// Negotiate client_max_window_bits attribute
    /**
     * When this method starts, m_client_max_window_bits and m_c2s_max_window_mode
     * will contain the server's preferred values for window size and
     * negotiation mode.
     *
     * options:
     * - decline (refuse to use the attribute)
     * - accept (use whatever the client says)
     * - largest (use largest possible value)
     * - smallest (use smallest possible value)
     *
     * @param [in] value The value of the attribute from the offer
     * @param [out] ec A reference to the error code to return errors via
     */
    void negotiate_client_max_window_bits(std::string const & value,
            lib::error_code & ec)
    {
        uint8_t bits = uint8_t(atoi(value.c_str()));

        if (value.empty()) {
            bits = default_client_max_window_bits;
        } else if (bits < min_client_max_window_bits ||
                   bits > max_client_max_window_bits)
        {
            ec = make_error_code(error::invalid_attribute_value);
            m_client_max_window_bits = default_client_max_window_bits;
            return;
        }

        switch (m_client_max_window_bits_mode) {
            case mode::decline:
                m_client_max_window_bits = default_client_max_window_bits;
                break;
            case mode::accept:
                m_client_max_window_bits = bits;
                break;
            case mode::largest:
                m_client_max_window_bits = std::min(bits,m_client_max_window_bits);
                break;
            case mode::smallest:
                m_client_max_window_bits = min_client_max_window_bits;
                break;
            default:
                ec = make_error_code(error::invalid_mode);
                m_client_max_window_bits = default_client_max_window_bits;
        }
    }

    bool m_enabled;
    bool m_server_no_context_takeover;
    bool m_client_no_context_takeover;
    uint8_t m_server_max_window_bits;
    uint8_t m_client_max_window_bits;
    mode::value m_server_max_window_bits_mode;
    mode::value m_client_max_window_bits_mode;

    bool m_initialized;
    int m_flush;
    size_t m_compress_buffer_size;
    lib::unique_ptr_uchar_array m_compress_buffer;
    z_stream m_dstate;
    z_stream m_istate;
};

} // namespace permessage_deflate
} // namespace extensions
} // namespace websocketpp

#endif // WEBSOCKETPP_PROCESSOR_EXTENSION_PERMESSAGEDEFLATE_HPP