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.

compress_snappy.py 17KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) Crossbar.io Technologies GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. from __future__ import absolute_import
  27. import snappy
  28. from autobahn.websocket.compress_base import PerMessageCompressOffer, \
  29. PerMessageCompressOfferAccept, \
  30. PerMessageCompressResponse, \
  31. PerMessageCompressResponseAccept, \
  32. PerMessageCompress
  33. __all__ = (
  34. 'PerMessageSnappyMixin',
  35. 'PerMessageSnappyOffer',
  36. 'PerMessageSnappyOfferAccept',
  37. 'PerMessageSnappyResponse',
  38. 'PerMessageSnappyResponseAccept',
  39. 'PerMessageSnappy',
  40. )
  41. class PerMessageSnappyMixin(object):
  42. """
  43. Mixin class for this extension.
  44. """
  45. EXTENSION_NAME = "permessage-snappy"
  46. """
  47. Name of this WebSocket extension.
  48. """
  49. class PerMessageSnappyOffer(PerMessageCompressOffer, PerMessageSnappyMixin):
  50. """
  51. Set of extension parameters for `permessage-snappy` WebSocket extension
  52. offered by a client to a server.
  53. """
  54. @classmethod
  55. def parse(cls, params):
  56. """
  57. Parses a WebSocket extension offer for `permessage-snappy` provided by a client to a server.
  58. :param params: Output from :func:`autobahn.websocket.WebSocketProtocol._parseExtensionsHeader`.
  59. :type params: list
  60. :returns: A new instance of :class:`autobahn.compress.PerMessageSnappyOffer`.
  61. :rtype: obj
  62. """
  63. # extension parameter defaults
  64. accept_no_context_takeover = False
  65. request_no_context_takeover = False
  66. # verify/parse client ("client-to-server direction") parameters of permessage-snappy offer
  67. for p in params:
  68. if len(params[p]) > 1:
  69. raise Exception("multiple occurrence of extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  70. val = params[p][0]
  71. if p == 'client_no_context_takeover':
  72. # noinspection PySimplifyBooleanCheck
  73. if val is not True:
  74. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  75. else:
  76. accept_no_context_takeover = True
  77. elif p == 'server_no_context_takeover':
  78. # noinspection PySimplifyBooleanCheck
  79. if val is not True:
  80. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  81. else:
  82. request_no_context_takeover = True
  83. else:
  84. raise Exception("illegal extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  85. offer = cls(accept_no_context_takeover,
  86. request_no_context_takeover)
  87. return offer
  88. def __init__(self,
  89. accept_no_context_takeover=True,
  90. request_no_context_takeover=False):
  91. """
  92. :param accept_no_context_takeover: Iff true, client accepts "no context takeover" feature.
  93. :type accept_no_context_takeover: bool
  94. :param request_no_context_takeover: Iff true, client request "no context takeover" feature.
  95. :type request_no_context_takeover: bool
  96. """
  97. if type(accept_no_context_takeover) != bool:
  98. raise Exception("invalid type %s for accept_no_context_takeover" % type(accept_no_context_takeover))
  99. self.accept_no_context_takeover = accept_no_context_takeover
  100. if type(request_no_context_takeover) != bool:
  101. raise Exception("invalid type %s for request_no_context_takeover" % type(request_no_context_takeover))
  102. self.request_no_context_takeover = request_no_context_takeover
  103. def get_extension_string(self):
  104. """
  105. Returns the WebSocket extension configuration string as sent to the server.
  106. :returns: PMCE configuration string.
  107. :rtype: str
  108. """
  109. pmce_string = self.EXTENSION_NAME
  110. if self.accept_no_context_takeover:
  111. pmce_string += "; client_no_context_takeover"
  112. if self.request_no_context_takeover:
  113. pmce_string += "; server_no_context_takeover"
  114. return pmce_string
  115. def __json__(self):
  116. """
  117. Returns a JSON serializable object representation.
  118. :returns: JSON serializable representation.
  119. :rtype: dict
  120. """
  121. return {'extension': self.EXTENSION_NAME,
  122. 'accept_no_context_takeover': self.accept_no_context_takeover,
  123. 'request_no_context_takeover': self.request_no_context_takeover}
  124. def __repr__(self):
  125. """
  126. Returns Python object representation that can be eval'ed to reconstruct the object.
  127. :returns: Python string representation.
  128. :rtype: str
  129. """
  130. return "PerMessageSnappyOffer(accept_no_context_takeover = %s, request_no_context_takeover = %s)" % (self.accept_no_context_takeover, self.request_no_context_takeover)
  131. class PerMessageSnappyOfferAccept(PerMessageCompressOfferAccept, PerMessageSnappyMixin):
  132. """
  133. Set of parameters with which to accept an `permessage-snappy` offer
  134. from a client by a server.
  135. """
  136. def __init__(self,
  137. offer,
  138. request_no_context_takeover=False,
  139. no_context_takeover=None):
  140. """
  141. :param offer: The offer being accepted.
  142. :type offer: Instance of :class:`autobahn.compress.PerMessageSnappyOffer`.
  143. :param request_no_context_takeover: Iff true, server request "no context takeover" feature.
  144. :type request_no_context_takeover: bool
  145. :param no_context_takeover: Override server ("server-to-client direction") context takeover (this must be compatible with offer).
  146. :type no_context_takeover: bool
  147. """
  148. if not isinstance(offer, PerMessageSnappyOffer):
  149. raise Exception("invalid type %s for offer" % type(offer))
  150. self.offer = offer
  151. if type(request_no_context_takeover) != bool:
  152. raise Exception("invalid type %s for request_no_context_takeover" % type(request_no_context_takeover))
  153. if request_no_context_takeover and not offer.accept_no_context_takeover:
  154. raise Exception("invalid value %s for request_no_context_takeover - feature unsupported by client" % request_no_context_takeover)
  155. self.request_no_context_takeover = request_no_context_takeover
  156. if no_context_takeover is not None:
  157. if type(no_context_takeover) != bool:
  158. raise Exception("invalid type %s for no_context_takeover" % type(no_context_takeover))
  159. if offer.request_no_context_takeover and not no_context_takeover:
  160. raise Exception("invalid value %s for no_context_takeover - client requested feature" % no_context_takeover)
  161. self.no_context_takeover = no_context_takeover
  162. def get_extension_string(self):
  163. """
  164. Returns the WebSocket extension configuration string as sent to the server.
  165. :returns: PMCE configuration string.
  166. :rtype: str
  167. """
  168. pmce_string = self.EXTENSION_NAME
  169. if self.offer.request_no_context_takeover:
  170. pmce_string += "; server_no_context_takeover"
  171. if self.request_no_context_takeover:
  172. pmce_string += "; client_no_context_takeover"
  173. return pmce_string
  174. def __json__(self):
  175. """
  176. Returns a JSON serializable object representation.
  177. :returns: JSON serializable representation.
  178. :rtype: dict
  179. """
  180. return {'extension': self.EXTENSION_NAME,
  181. 'offer': self.offer.__json__(),
  182. 'request_no_context_takeover': self.request_no_context_takeover,
  183. 'no_context_takeover': self.no_context_takeover}
  184. def __repr__(self):
  185. """
  186. Returns Python object representation that can be eval'ed to reconstruct the object.
  187. :returns: Python string representation.
  188. :rtype: str
  189. """
  190. return "PerMessageSnappyAccept(offer = %s, request_no_context_takeover = %s, no_context_takeover = %s)" % (self.offer.__repr__(), self.request_no_context_takeover, self.no_context_takeover)
  191. class PerMessageSnappyResponse(PerMessageCompressResponse, PerMessageSnappyMixin):
  192. """
  193. Set of parameters for `permessage-snappy` responded by server.
  194. """
  195. @classmethod
  196. def parse(cls, params):
  197. """
  198. Parses a WebSocket extension response for `permessage-snappy` provided by a server to a client.
  199. :param params: Output from :func:`autobahn.websocket.WebSocketProtocol._parseExtensionsHeader`.
  200. :type params: list
  201. :returns: A new instance of :class:`autobahn.compress.PerMessageSnappyResponse`.
  202. :rtype: obj
  203. """
  204. client_no_context_takeover = False
  205. server_no_context_takeover = False
  206. for p in params:
  207. if len(params[p]) > 1:
  208. raise Exception("multiple occurrence of extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  209. val = params[p][0]
  210. if p == 'client_no_context_takeover':
  211. # noinspection PySimplifyBooleanCheck
  212. if val is not True:
  213. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  214. else:
  215. client_no_context_takeover = True
  216. elif p == 'server_no_context_takeover':
  217. # noinspection PySimplifyBooleanCheck
  218. if val is not True:
  219. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  220. else:
  221. server_no_context_takeover = True
  222. else:
  223. raise Exception("illegal extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  224. response = cls(client_no_context_takeover,
  225. server_no_context_takeover)
  226. return response
  227. def __init__(self,
  228. client_no_context_takeover,
  229. server_no_context_takeover):
  230. self.client_no_context_takeover = client_no_context_takeover
  231. self.server_no_context_takeover = server_no_context_takeover
  232. def __json__(self):
  233. """
  234. Returns a JSON serializable object representation.
  235. :returns: JSON serializable representation.
  236. :rtype: dict
  237. """
  238. return {'extension': self.EXTENSION_NAME,
  239. 'client_no_context_takeover': self.client_no_context_takeover,
  240. 'server_no_context_takeover': self.server_no_context_takeover}
  241. def __repr__(self):
  242. """
  243. Returns Python object representation that can be eval'ed to reconstruct the object.
  244. :returns: Python string representation.
  245. :rtype: str
  246. """
  247. return "PerMessageSnappyResponse(client_no_context_takeover = %s, server_no_context_takeover = %s)" % (self.client_no_context_takeover, self.server_no_context_takeover)
  248. class PerMessageSnappyResponseAccept(PerMessageCompressResponseAccept, PerMessageSnappyMixin):
  249. """
  250. Set of parameters with which to accept an `permessage-snappy` response
  251. from a server by a client.
  252. """
  253. def __init__(self,
  254. response,
  255. no_context_takeover=None):
  256. """
  257. :param response: The response being accepted.
  258. :type response: Instance of :class:`autobahn.compress.PerMessageSnappyResponse`.
  259. :param no_context_takeover: Override client ("client-to-server direction") context takeover (this must be compatible with response).
  260. :type no_context_takeover: bool
  261. """
  262. if not isinstance(response, PerMessageSnappyResponse):
  263. raise Exception("invalid type %s for response" % type(response))
  264. self.response = response
  265. if no_context_takeover is not None:
  266. if type(no_context_takeover) != bool:
  267. raise Exception("invalid type %s for no_context_takeover" % type(no_context_takeover))
  268. if response.client_no_context_takeover and not no_context_takeover:
  269. raise Exception("invalid value %s for no_context_takeover - server requested feature" % no_context_takeover)
  270. self.no_context_takeover = no_context_takeover
  271. def __json__(self):
  272. """
  273. Returns a JSON serializable object representation.
  274. :returns: JSON serializable representation.
  275. :rtype: dict
  276. """
  277. return {'extension': self.EXTENSION_NAME,
  278. 'response': self.response.__json__(),
  279. 'no_context_takeover': self.no_context_takeover}
  280. def __repr__(self):
  281. """
  282. Returns Python object representation that can be eval'ed to reconstruct the object.
  283. :returns: Python string representation.
  284. :rtype: str
  285. """
  286. return "PerMessageSnappyResponseAccept(response = %s, no_context_takeover = %s)" % (self.response.__repr__(), self.no_context_takeover)
  287. class PerMessageSnappy(PerMessageCompress, PerMessageSnappyMixin):
  288. """
  289. `permessage-snappy` WebSocket extension processor.
  290. """
  291. @classmethod
  292. def create_from_response_accept(cls, is_server, accept):
  293. pmce = cls(is_server,
  294. accept.response.server_no_context_takeover,
  295. accept.no_context_takeover if accept.no_context_takeover is not None else accept.response.client_no_context_takeover)
  296. return pmce
  297. @classmethod
  298. def create_from_offer_accept(cls, is_server, accept):
  299. pmce = cls(is_server,
  300. accept.no_context_takeover if accept.no_context_takeover is not None else accept.offer.request_no_context_takeover,
  301. accept.request_no_context_takeover)
  302. return pmce
  303. def __init__(self,
  304. is_server,
  305. server_no_context_takeover,
  306. client_no_context_takeover):
  307. self._is_server = is_server
  308. self.server_no_context_takeover = server_no_context_takeover
  309. self.client_no_context_takeover = client_no_context_takeover
  310. self._compressor = None
  311. self._decompressor = None
  312. def __json__(self):
  313. return {'extension': self.EXTENSION_NAME,
  314. 'server_no_context_takeover': self.server_no_context_takeover,
  315. 'client_no_context_takeover': self.client_no_context_takeover}
  316. def __repr__(self):
  317. return "PerMessageSnappy(is_server = %s, server_no_context_takeover = %s, client_no_context_takeover = %s)" % (self._is_server, self.server_no_context_takeover, self.client_no_context_takeover)
  318. def start_compress_message(self):
  319. if self._is_server:
  320. if self._compressor is None or self.server_no_context_takeover:
  321. self._compressor = snappy.StreamCompressor()
  322. else:
  323. if self._compressor is None or self.client_no_context_takeover:
  324. self._compressor = snappy.StreamCompressor()
  325. def compress_message_data(self, data):
  326. return self._compressor.add_chunk(data)
  327. def end_compress_message(self):
  328. return b""
  329. def start_decompress_message(self):
  330. if self._is_server:
  331. if self._decompressor is None or self.client_no_context_takeover:
  332. self._decompressor = snappy.StreamDecompressor()
  333. else:
  334. if self._decompressor is None or self.server_no_context_takeover:
  335. self._decompressor = snappy.StreamDecompressor()
  336. def decompress_message_data(self, data):
  337. return self._decompressor.decompress(data)
  338. def end_decompress_message(self):
  339. pass