You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

852 lines
28 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2015, Peter Thorson. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. * * Neither the name of the WebSocket++ Project nor the
  12. * names of its contributors may be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
  19. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. *
  26. */
  27. #ifndef WEBSOCKETPP_PROCESSOR_EXTENSION_PERMESSAGEDEFLATE_HPP
  28. #define WEBSOCKETPP_PROCESSOR_EXTENSION_PERMESSAGEDEFLATE_HPP
  29. #include "zlib.h"
  30. #include <algorithm>
  31. #include <string>
  32. #include <vector>
  33. #include <websocketpp/common/cpp11.hpp>
  34. #include <websocketpp/common/memory.hpp>
  35. #include <websocketpp/common/platforms.hpp>
  36. #include <websocketpp/common/stdint.hpp>
  37. #include <websocketpp/common/system_error.hpp>
  38. #include <websocketpp/error.hpp>
  39. #include <websocketpp/extensions/extension.hpp>
  40. namespace websocketpp
  41. {
  42. namespace extensions
  43. {
  44. /// Implementation of RFC 7692, the permessage-deflate WebSocket extension
  45. /**
  46. * ### permessage-deflate interface
  47. *
  48. * **init**\n
  49. * `lib::error_code init(bool is_server)`\n
  50. * Performs initialization
  51. *
  52. * **is_implimented**\n
  53. * `bool is_implimented()`\n
  54. * Returns whether or not the object impliments the extension or not
  55. *
  56. * **is_enabled**\n
  57. * `bool is_enabled()`\n
  58. * Returns whether or not the extension was negotiated for the current
  59. * connection
  60. *
  61. * **generate_offer**\n
  62. * `std::string generate_offer() const`\n
  63. * Create an extension offer string based on local policy
  64. *
  65. * **validate_response**\n
  66. * `lib::error_code validate_response(http::attribute_list const & response)`\n
  67. * Negotiate the parameters of extension use
  68. *
  69. * **negotiate**\n
  70. * `err_str_pair negotiate(http::attribute_list const & attributes)`\n
  71. * Negotiate the parameters of extension use
  72. *
  73. * **compress**\n
  74. * `lib::error_code compress(std::string const & in, std::string & out)`\n
  75. * Compress the bytes in `in` and append them to `out`
  76. *
  77. * **decompress**\n
  78. * `lib::error_code decompress(uint8_t const * buf, size_t len, std::string &
  79. * out)`\n
  80. * Decompress `len` bytes from `buf` and append them to string `out`
  81. */
  82. namespace permessage_deflate
  83. {
  84. /// Permessage deflate error values
  85. namespace error
  86. {
  87. enum value
  88. {
  89. /// Catch all
  90. general = 1,
  91. /// Invalid extension attributes
  92. invalid_attributes,
  93. /// Invalid extension attribute value
  94. invalid_attribute_value,
  95. /// Invalid megotiation mode
  96. invalid_mode,
  97. /// Unsupported extension attributes
  98. unsupported_attributes,
  99. /// Invalid value for max_window_bits
  100. invalid_max_window_bits,
  101. /// ZLib Error
  102. zlib_error,
  103. /// Uninitialized
  104. uninitialized,
  105. };
  106. /// Permessage-deflate error category
  107. class category : public lib::error_category
  108. {
  109. public:
  110. category() {}
  111. const char * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_
  112. {
  113. return "websocketpp.extension.permessage-deflate";
  114. }
  115. std::string message(int value) const
  116. {
  117. switch (value)
  118. {
  119. case general : return "Generic permessage-compress error";
  120. case invalid_attributes : return "Invalid extension attributes";
  121. case invalid_attribute_value: return "Invalid extension attribute value";
  122. case invalid_mode : return "Invalid permessage-deflate negotiation mode";
  123. case unsupported_attributes : return "Unsupported extension attributes";
  124. case invalid_max_window_bits: return "Invalid value for max_window_bits";
  125. case zlib_error : return "A zlib function returned an error";
  126. case uninitialized : return "Deflate extension must be initialized before use";
  127. default : return "Unknown permessage-compress error";
  128. }
  129. }
  130. };
  131. /// Get a reference to a static copy of the permessage-deflate error category
  132. inline const lib::error_category & get_category()
  133. {
  134. static category instance;
  135. return instance;
  136. }
  137. /// Create an error code in the permessage-deflate category
  138. inline lib::error_code make_error_code(error::value e)
  139. {
  140. return lib::error_code(static_cast<int>(e), get_category());
  141. }
  142. } // namespace error
  143. } // namespace permessage_deflate
  144. } // namespace extensions
  145. } // namespace websocketpp
  146. _WEBSOCKETPP_ERROR_CODE_ENUM_NS_START_
  147. template <> struct is_error_code_enum<websocketpp::extensions::permessage_deflate::error::value>
  148. {
  149. static const bool value = true;
  150. };
  151. _WEBSOCKETPP_ERROR_CODE_ENUM_NS_END_
  152. namespace websocketpp
  153. {
  154. namespace extensions
  155. {
  156. namespace permessage_deflate
  157. {
  158. /// Default value for server_max_window_bits as defined by RFC 7692
  159. static const uint8_t default_server_max_window_bits = 15;
  160. /// Minimum value for server_max_window_bits as defined by RFC 7692
  161. /**
  162. * NOTE: A value of 8 is not actually supported by zlib, the deflate
  163. * library that WebSocket++ uses. To preserve backwards compatibility
  164. * with RFC 7692 and previous versions of the library a value of 8
  165. * is accepted by the library but will always be negotiated as 9.
  166. */
  167. static const uint8_t min_server_max_window_bits = 8;
  168. /// Maximum value for server_max_window_bits as defined by RFC 7692
  169. static const uint8_t max_server_max_window_bits = 15;
  170. /// Default value for client_max_window_bits as defined by RFC 7692
  171. static const uint8_t default_client_max_window_bits = 15;
  172. /// Minimum value for client_max_window_bits as defined by RFC 7692
  173. /**
  174. * NOTE: A value of 8 is not actually supported by zlib, the deflate
  175. * library that WebSocket++ uses. To preserve backwards compatibility
  176. * with RFC 7692 and previous versions of the library a value of 8
  177. * is accepted by the library but will always be negotiated as 9.
  178. */
  179. static const uint8_t min_client_max_window_bits = 8;
  180. /// Maximum value for client_max_window_bits as defined by RFC 7692
  181. static const uint8_t max_client_max_window_bits = 15;
  182. namespace mode
  183. {
  184. enum value
  185. {
  186. /// Accept any value the remote endpoint offers
  187. accept = 1,
  188. /// Decline any value the remote endpoint offers. Insist on defaults.
  189. decline,
  190. /// Use the largest value common to both offers
  191. largest,
  192. /// Use the smallest value common to both offers
  193. smallest
  194. };
  195. } // namespace mode
  196. template <typename config> class enabled
  197. {
  198. public:
  199. enabled() :
  200. m_enabled(false),
  201. m_server_no_context_takeover(false),
  202. m_client_no_context_takeover(false),
  203. m_server_max_window_bits(15),
  204. m_client_max_window_bits(15),
  205. m_server_max_window_bits_mode(mode::accept),
  206. m_client_max_window_bits_mode(mode::accept),
  207. m_initialized(false),
  208. m_compress_buffer_size(8192)
  209. {
  210. m_dstate.zalloc = Z_NULL;
  211. m_dstate.zfree = Z_NULL;
  212. m_dstate.opaque = Z_NULL;
  213. m_istate.zalloc = Z_NULL;
  214. m_istate.zfree = Z_NULL;
  215. m_istate.opaque = Z_NULL;
  216. m_istate.avail_in = 0;
  217. m_istate.next_in = Z_NULL;
  218. }
  219. ~enabled()
  220. {
  221. if (! m_initialized)
  222. {
  223. return;
  224. }
  225. int ret = deflateEnd(&m_dstate);
  226. if (ret != Z_OK)
  227. {
  228. // std::cout << "error cleaning up zlib compression state"
  229. // << std::endl;
  230. }
  231. ret = inflateEnd(&m_istate);
  232. if (ret != Z_OK)
  233. {
  234. // std::cout << "error cleaning up zlib decompression state"
  235. // << std::endl;
  236. }
  237. }
  238. /// Initialize zlib state
  239. /**
  240. * Note: this should be called *after* the negotiation methods. It will use
  241. * information from the negotiation to determine how to initialize the zlib
  242. * data structures.
  243. *
  244. * @todo memory level, strategy, etc are hardcoded
  245. *
  246. * @param is_server True to initialize as a server, false for a client.
  247. * @return A code representing the error that occurred, if any
  248. */
  249. lib::error_code init(bool is_server)
  250. {
  251. uint8_t deflate_bits;
  252. uint8_t inflate_bits;
  253. if (is_server)
  254. {
  255. deflate_bits = m_server_max_window_bits;
  256. inflate_bits = m_client_max_window_bits;
  257. }
  258. else
  259. {
  260. deflate_bits = m_client_max_window_bits;
  261. inflate_bits = m_server_max_window_bits;
  262. }
  263. int ret = deflateInit2(&m_dstate, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -1 * deflate_bits,
  264. 4, // memory level 1-9
  265. Z_DEFAULT_STRATEGY);
  266. if (ret != Z_OK)
  267. {
  268. return make_error_code(error::zlib_error);
  269. }
  270. ret = inflateInit2(&m_istate, -1 * inflate_bits);
  271. if (ret != Z_OK)
  272. {
  273. return make_error_code(error::zlib_error);
  274. }
  275. m_compress_buffer.reset(new unsigned char[m_compress_buffer_size]);
  276. m_decompress_buffer.reset(new unsigned char[m_compress_buffer_size]);
  277. if ((m_server_no_context_takeover && is_server) || (m_client_no_context_takeover && ! is_server))
  278. {
  279. m_flush = Z_FULL_FLUSH;
  280. }
  281. else
  282. {
  283. m_flush = Z_SYNC_FLUSH;
  284. }
  285. m_initialized = true;
  286. return lib::error_code();
  287. }
  288. /// Test if this object implements the permessage-deflate specification
  289. /**
  290. * Because this object does implieent it, it will always return true.
  291. *
  292. * @return Whether or not this object implements permessage-deflate
  293. */
  294. bool is_implemented() const
  295. {
  296. return true;
  297. }
  298. /// Test if the extension was negotiated for this connection
  299. /**
  300. * Retrieves whether or not this extension is in use based on the initial
  301. * handshake extension negotiations.
  302. *
  303. * @return Whether or not the extension is in use
  304. */
  305. bool is_enabled() const
  306. {
  307. return m_enabled;
  308. }
  309. /// Reset server's outgoing LZ77 sliding window for each new message
  310. /**
  311. * Enabling this setting will cause the server's compressor to reset the
  312. * compression state (the LZ77 sliding window) for every message. This
  313. * means that the compressor will not look back to patterns in previous
  314. * messages to improve compression. This will reduce the compression
  315. * efficiency for large messages somewhat and small messages drastically.
  316. *
  317. * This option may reduce server compressor memory usage and client
  318. * decompressor memory usage.
  319. * @todo Document to what extent memory usage will be reduced
  320. *
  321. * For clients, this option is dependent on server support. Enabling it
  322. * via this method does not guarantee that it will be successfully
  323. * negotiated, only that it will be requested.
  324. *
  325. * For servers, no client support is required. Enabling this option on a
  326. * server will result in its use. The server will signal to clients that
  327. * the option will be in use so they can optimize resource usage if they
  328. * are able.
  329. */
  330. void enable_server_no_context_takeover()
  331. {
  332. m_server_no_context_takeover = true;
  333. }
  334. /// Reset client's outgoing LZ77 sliding window for each new message
  335. /**
  336. * Enabling this setting will cause the client's compressor to reset the
  337. * compression state (the LZ77 sliding window) for every message. This
  338. * means that the compressor will not look back to patterns in previous
  339. * messages to improve compression. This will reduce the compression
  340. * efficiency for large messages somewhat and small messages drastically.
  341. *
  342. * This option may reduce client compressor memory usage and server
  343. * decompressor memory usage.
  344. * @todo Document to what extent memory usage will be reduced
  345. *
  346. * This option is supported by all compliant clients and servers. Enabling
  347. * it via either endpoint should be sufficient to ensure it is used.
  348. */
  349. void enable_client_no_context_takeover()
  350. {
  351. m_client_no_context_takeover = true;
  352. }
  353. /// Limit server LZ77 sliding window size
  354. /**
  355. * The bits setting is the base 2 logarithm of the maximum window size that
  356. * the server must use to compress outgoing messages. The permitted range
  357. * is 9 to 15 inclusive. 9 represents a 512 byte window and 15 a 32KiB
  358. * window. The default setting is 15.
  359. *
  360. * Mode Options:
  361. * - accept: Accept whatever the remote endpoint offers.
  362. * - decline: Decline any offers to deviate from the defaults
  363. * - largest: Accept largest window size acceptable to both endpoints
  364. * - smallest: Accept smallest window size acceptiable to both endpoints
  365. *
  366. * This setting is dependent on server support. A client requesting this
  367. * setting may be rejected by the server or have the exact value used
  368. * adjusted by the server. A server may unilaterally set this value without
  369. * client support.
  370. *
  371. * NOTE: The permessage-deflate spec specifies that a value of 8 is allowed.
  372. * Prior to version 0.8.0 a value of 8 was also allowed by this library.
  373. * zlib, the deflate compression library that WebSocket++ uses has always
  374. * silently adjusted a value of 8 to 9. In recent versions of zlib (1.2.9
  375. * and greater) a value of 8 is now explicitly rejected. WebSocket++ 0.8.0
  376. * continues to perform the 8->9 conversion for backwards compatibility
  377. * purposes but this should be considered deprecated functionality.
  378. *
  379. * @param bits The size to request for the outgoing window size
  380. * @param mode The mode to use for negotiating this parameter
  381. * @return A status code
  382. */
  383. lib::error_code set_server_max_window_bits(uint8_t bits, mode::value mode)
  384. {
  385. if (bits < min_server_max_window_bits || bits > max_server_max_window_bits)
  386. {
  387. return error::make_error_code(error::invalid_max_window_bits);
  388. }
  389. // See note in doc comment above about what is happening here
  390. if (bits == 8)
  391. {
  392. bits = 9;
  393. }
  394. m_server_max_window_bits = bits;
  395. m_server_max_window_bits_mode = mode;
  396. return lib::error_code();
  397. }
  398. /// Limit client LZ77 sliding window size
  399. /**
  400. * The bits setting is the base 2 logarithm of the window size that the
  401. * client must use to compress outgoing messages. The permitted range is 9
  402. * to 15 inclusive. 9 represents a 512 byte window and 15 a 32KiB window.
  403. * The default setting is 15.
  404. *
  405. * Mode Options:
  406. * - accept: Accept whatever the remote endpoint offers.
  407. * - decline: Decline any offers to deviate from the defaults
  408. * - largest: Accept largest window size acceptable to both endpoints
  409. * - smallest: Accept smallest window size acceptiable to both endpoints
  410. *
  411. * This setting is dependent on client support. A client may limit its own
  412. * outgoing window size unilaterally. A server may only limit the client's
  413. * window size if the remote client supports that feature.
  414. *
  415. * NOTE: The permessage-deflate spec specifies that a value of 8 is allowed.
  416. * Prior to version 0.8.0 a value of 8 was also allowed by this library.
  417. * zlib, the deflate compression library that WebSocket++ uses has always
  418. * silently adjusted a value of 8 to 9. In recent versions of zlib (1.2.9
  419. * and greater) a value of 8 is now explicitly rejected. WebSocket++ 0.8.0
  420. * continues to perform the 8->9 conversion for backwards compatibility
  421. * purposes but this should be considered deprecated functionality.
  422. *
  423. * @param bits The size to request for the outgoing window size
  424. * @param mode The mode to use for negotiating this parameter
  425. * @return A status code
  426. */
  427. lib::error_code set_client_max_window_bits(uint8_t bits, mode::value mode)
  428. {
  429. if (bits < min_client_max_window_bits || bits > max_client_max_window_bits)
  430. {
  431. return error::make_error_code(error::invalid_max_window_bits);
  432. }
  433. // See note in doc comment above about what is happening here
  434. if (bits == 8)
  435. {
  436. bits = 9;
  437. }
  438. m_client_max_window_bits = bits;
  439. m_client_max_window_bits_mode = mode;
  440. return lib::error_code();
  441. }
  442. /// Generate extension offer
  443. /**
  444. * Creates an offer string to include in the Sec-WebSocket-Extensions
  445. * header of outgoing client requests.
  446. *
  447. * @return A WebSocket extension offer string for this extension
  448. */
  449. std::string generate_offer() const
  450. {
  451. // TODO: this should be dynamically generated based on user settings
  452. return "permessage-deflate; client_no_context_takeover; client_max_window_bits";
  453. }
  454. /// Validate extension response
  455. /**
  456. * Confirm that the server has negotiated settings compatible with our
  457. * original offer and apply those settings to the extension state.
  458. *
  459. * @param response The server response attribute list to validate
  460. * @return Validation error or 0 on success
  461. */
  462. lib::error_code validate_offer(const http::attribute_list &)
  463. {
  464. return lib::error_code();
  465. }
  466. /// Negotiate extension
  467. /**
  468. * Confirm that the client's extension negotiation offer has settings
  469. * compatible with local policy. If so, generate a reply and apply those
  470. * settings to the extension state.
  471. *
  472. * @param offer Attribute from client's offer
  473. * @return Status code and value to return to remote endpoint
  474. */
  475. err_str_pair negotiate(const http::attribute_list & offer)
  476. {
  477. err_str_pair ret;
  478. http::attribute_list::const_iterator it;
  479. for (it = offer.begin(); it != offer.end(); ++it)
  480. {
  481. if (it->first == "server_no_context_takeover")
  482. {
  483. negotiate_server_no_context_takeover(it->second, ret.first);
  484. }
  485. else if (it->first == "client_no_context_takeover")
  486. {
  487. negotiate_client_no_context_takeover(it->second, ret.first);
  488. }
  489. else if (it->first == "server_max_window_bits")
  490. {
  491. negotiate_server_max_window_bits(it->second, ret.first);
  492. }
  493. else if (it->first == "client_max_window_bits")
  494. {
  495. negotiate_client_max_window_bits(it->second, ret.first);
  496. }
  497. else
  498. {
  499. ret.first = make_error_code(error::invalid_attributes);
  500. }
  501. if (ret.first)
  502. {
  503. break;
  504. }
  505. }
  506. if (ret.first == lib::error_code())
  507. {
  508. m_enabled = true;
  509. ret.second = generate_response();
  510. }
  511. return ret;
  512. }
  513. /// Compress bytes
  514. /**
  515. * @todo: avail_in/out is 32 bit, need to fix for cases of >32 bit frames
  516. * on 64 bit machines.
  517. *
  518. * @param [in] in String to compress
  519. * @param [out] out String to append compressed bytes to
  520. * @return Error or status code
  521. */
  522. lib::error_code compress(const std::string & in, std::string & out)
  523. {
  524. if (! m_initialized)
  525. {
  526. return make_error_code(error::uninitialized);
  527. }
  528. size_t output;
  529. if (in.empty())
  530. {
  531. uint8_t buf[6] = {0x02, 0x00, 0x00, 0x00, 0xff, 0xff};
  532. out.append((char *) (buf), 6);
  533. return lib::error_code();
  534. }
  535. m_dstate.avail_in = in.size();
  536. m_dstate.next_in = (unsigned char *) (const_cast<char *>(in.data()));
  537. do
  538. {
  539. // Output to local buffer
  540. m_dstate.avail_out = m_compress_buffer_size;
  541. m_dstate.next_out = m_compress_buffer.get();
  542. deflate(&m_dstate, m_flush);
  543. output = m_compress_buffer_size - m_dstate.avail_out;
  544. out.append((char *) (m_compress_buffer.get()), output);
  545. }
  546. while (m_dstate.avail_out == 0);
  547. return lib::error_code();
  548. }
  549. /// Decompress bytes
  550. /**
  551. * @param buf Byte buffer to decompress
  552. * @param len Length of buf
  553. * @param out String to append decompressed bytes to
  554. * @return Error or status code
  555. */
  556. lib::error_code decompress(const uint8_t * buf, size_t len, std::string & out)
  557. {
  558. if (! m_initialized)
  559. {
  560. return make_error_code(error::uninitialized);
  561. }
  562. int ret;
  563. m_istate.avail_in = len;
  564. m_istate.next_in = const_cast<unsigned char *>(buf);
  565. do
  566. {
  567. m_istate.avail_out = m_compress_buffer_size;
  568. m_istate.next_out = m_decompress_buffer.get();
  569. ret = inflate(&m_istate, Z_SYNC_FLUSH);
  570. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR)
  571. {
  572. return make_error_code(error::zlib_error);
  573. }
  574. out.append(reinterpret_cast<char *>(m_decompress_buffer.get()), m_compress_buffer_size - m_istate.avail_out);
  575. }
  576. while (m_istate.avail_out == 0);
  577. return lib::error_code();
  578. }
  579. private:
  580. /// Generate negotiation response
  581. /**
  582. * @return Generate extension negotiation reponse string to send to client
  583. */
  584. std::string generate_response()
  585. {
  586. std::string ret = "permessage-deflate";
  587. if (m_server_no_context_takeover)
  588. {
  589. ret += "; server_no_context_takeover";
  590. }
  591. if (m_client_no_context_takeover)
  592. {
  593. ret += "; client_no_context_takeover";
  594. }
  595. if (m_server_max_window_bits < default_server_max_window_bits)
  596. {
  597. std::stringstream s;
  598. s << int(m_server_max_window_bits);
  599. ret += "; server_max_window_bits=" + s.str();
  600. }
  601. if (m_client_max_window_bits < default_client_max_window_bits)
  602. {
  603. std::stringstream s;
  604. s << int(m_client_max_window_bits);
  605. ret += "; client_max_window_bits=" + s.str();
  606. }
  607. return ret;
  608. }
  609. /// Negotiate server_no_context_takeover attribute
  610. /**
  611. * @param [in] value The value of the attribute from the offer
  612. * @param [out] ec A reference to the error code to return errors via
  613. */
  614. void negotiate_server_no_context_takeover(const std::string & value, lib::error_code & ec)
  615. {
  616. if (! value.empty())
  617. {
  618. ec = make_error_code(error::invalid_attribute_value);
  619. return;
  620. }
  621. m_server_no_context_takeover = true;
  622. }
  623. /// Negotiate client_no_context_takeover attribute
  624. /**
  625. * @param [in] value The value of the attribute from the offer
  626. * @param [out] ec A reference to the error code to return errors via
  627. */
  628. void negotiate_client_no_context_takeover(const std::string & value, lib::error_code & ec)
  629. {
  630. if (! value.empty())
  631. {
  632. ec = make_error_code(error::invalid_attribute_value);
  633. return;
  634. }
  635. m_client_no_context_takeover = true;
  636. }
  637. /// Negotiate server_max_window_bits attribute
  638. /**
  639. * When this method starts, m_server_max_window_bits will contain the server's
  640. * preferred value and m_server_max_window_bits_mode will contain the mode the
  641. * server wants to use to for negotiation. `value` contains the value the
  642. * client requested that we use.
  643. *
  644. * options:
  645. * - decline (ignore value, offer our default instead)
  646. * - accept (use the value requested by the client)
  647. * - largest (use largest value acceptable to both)
  648. * - smallest (use smallest possible value)
  649. *
  650. * NOTE: As a value of 8 is no longer explicitly supported by zlib but might
  651. * be requested for negotiation by an older client/server, if the result of
  652. * the negotiation would be to send a value of 8, a value of 9 is offered
  653. * instead. This ensures that WebSocket++ will only ever negotiate connections
  654. * with compression settings explicitly supported by zlib.
  655. *
  656. * @param [in] value The value of the attribute from the offer
  657. * @param [out] ec A reference to the error code to return errors via
  658. */
  659. void negotiate_server_max_window_bits(const std::string & value, lib::error_code & ec)
  660. {
  661. uint8_t bits = uint8_t(atoi(value.c_str()));
  662. if (bits < min_server_max_window_bits || bits > max_server_max_window_bits)
  663. {
  664. ec = make_error_code(error::invalid_attribute_value);
  665. m_server_max_window_bits = default_server_max_window_bits;
  666. return;
  667. }
  668. switch (m_server_max_window_bits_mode)
  669. {
  670. case mode::decline : m_server_max_window_bits = default_server_max_window_bits; break;
  671. case mode::accept : m_server_max_window_bits = bits; break;
  672. case mode::largest : m_server_max_window_bits = std::min(bits, m_server_max_window_bits); break;
  673. case mode::smallest: m_server_max_window_bits = min_server_max_window_bits; break;
  674. default : ec = make_error_code(error::invalid_mode); m_server_max_window_bits = default_server_max_window_bits;
  675. }
  676. // See note in doc comment
  677. if (m_server_max_window_bits == 8)
  678. {
  679. m_server_max_window_bits = 9;
  680. }
  681. }
  682. /// Negotiate client_max_window_bits attribute
  683. /**
  684. * When this method starts, m_client_max_window_bits and m_c2s_max_window_mode
  685. * will contain the server's preferred values for window size and
  686. * negotiation mode.
  687. *
  688. * options:
  689. * - decline (ignore value, offer our default instead)
  690. * - accept (use the value requested by the client)
  691. * - largest (use largest value acceptable to both)
  692. * - smallest (use smallest possible value)
  693. *
  694. * NOTE: As a value of 8 is no longer explicitly supported by zlib but might
  695. * be requested for negotiation by an older client/server, if the result of
  696. * the negotiation would be to send a value of 8, a value of 9 is offered
  697. * instead. This ensures that WebSocket++ will only ever negotiate connections
  698. * with compression settings explicitly supported by zlib.
  699. *
  700. * @param [in] value The value of the attribute from the offer
  701. * @param [out] ec A reference to the error code to return errors via
  702. */
  703. void negotiate_client_max_window_bits(const std::string & value, lib::error_code & ec)
  704. {
  705. uint8_t bits = uint8_t(atoi(value.c_str()));
  706. if (value.empty())
  707. {
  708. bits = default_client_max_window_bits;
  709. }
  710. else if (bits < min_client_max_window_bits || bits > max_client_max_window_bits)
  711. {
  712. ec = make_error_code(error::invalid_attribute_value);
  713. m_client_max_window_bits = default_client_max_window_bits;
  714. return;
  715. }
  716. switch (m_client_max_window_bits_mode)
  717. {
  718. case mode::decline : m_client_max_window_bits = default_client_max_window_bits; break;
  719. case mode::accept : m_client_max_window_bits = bits; break;
  720. case mode::largest : m_client_max_window_bits = std::min(bits, m_client_max_window_bits); break;
  721. case mode::smallest: m_client_max_window_bits = min_client_max_window_bits; break;
  722. default : ec = make_error_code(error::invalid_mode); m_client_max_window_bits = default_client_max_window_bits;
  723. }
  724. // See note in doc comment
  725. if (m_client_max_window_bits == 8)
  726. {
  727. m_client_max_window_bits = 9;
  728. }
  729. }
  730. bool m_enabled;
  731. bool m_server_no_context_takeover;
  732. bool m_client_no_context_takeover;
  733. uint8_t m_server_max_window_bits;
  734. uint8_t m_client_max_window_bits;
  735. mode::value m_server_max_window_bits_mode;
  736. mode::value m_client_max_window_bits_mode;
  737. bool m_initialized;
  738. int m_flush;
  739. size_t m_compress_buffer_size;
  740. lib::unique_ptr_uchar_array m_compress_buffer;
  741. lib::unique_ptr_uchar_array m_decompress_buffer;
  742. z_stream m_dstate;
  743. z_stream m_istate;
  744. };
  745. } // namespace permessage_deflate
  746. } // namespace extensions
  747. } // namespace websocketpp
  748. #endif // WEBSOCKETPP_PROCESSOR_EXTENSION_PERMESSAGEDEFLATE_HPP