Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int 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. import snappy
  27. from autobahn.websocket.compress_base import PerMessageCompressOffer, \
  28. PerMessageCompressOfferAccept, \
  29. PerMessageCompressResponse, \
  30. PerMessageCompressResponseAccept, \
  31. PerMessageCompress
  32. __all__ = (
  33. 'PerMessageSnappyMixin',
  34. 'PerMessageSnappyOffer',
  35. 'PerMessageSnappyOfferAccept',
  36. 'PerMessageSnappyResponse',
  37. 'PerMessageSnappyResponseAccept',
  38. 'PerMessageSnappy',
  39. )
  40. class PerMessageSnappyMixin(object):
  41. """
  42. Mixin class for this extension.
  43. """
  44. EXTENSION_NAME = "permessage-snappy"
  45. """
  46. Name of this WebSocket extension.
  47. """
  48. class PerMessageSnappyOffer(PerMessageCompressOffer, PerMessageSnappyMixin):
  49. """
  50. Set of extension parameters for `permessage-snappy` WebSocket extension
  51. offered by a client to a server.
  52. """
  53. @classmethod
  54. def parse(cls, params):
  55. """
  56. Parses a WebSocket extension offer for `permessage-snappy` provided by a client to a server.
  57. :param params: Output from :func:`autobahn.websocket.WebSocketProtocol._parseExtensionsHeader`.
  58. :type params: list
  59. :returns: A new instance of :class:`autobahn.compress.PerMessageSnappyOffer`.
  60. :rtype: obj
  61. """
  62. # extension parameter defaults
  63. accept_no_context_takeover = False
  64. request_no_context_takeover = False
  65. # verify/parse client ("client-to-server direction") parameters of permessage-snappy offer
  66. for p in params:
  67. if len(params[p]) > 1:
  68. raise Exception("multiple occurrence of extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  69. val = params[p][0]
  70. if p == 'client_no_context_takeover':
  71. # noinspection PySimplifyBooleanCheck
  72. if val is not True:
  73. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  74. else:
  75. accept_no_context_takeover = True
  76. elif p == 'server_no_context_takeover':
  77. # noinspection PySimplifyBooleanCheck
  78. if val is not True:
  79. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  80. else:
  81. request_no_context_takeover = True
  82. else:
  83. raise Exception("illegal extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  84. offer = cls(accept_no_context_takeover,
  85. request_no_context_takeover)
  86. return offer
  87. def __init__(self,
  88. accept_no_context_takeover=True,
  89. request_no_context_takeover=False):
  90. """
  91. :param accept_no_context_takeover: Iff true, client accepts "no context takeover" feature.
  92. :type accept_no_context_takeover: bool
  93. :param request_no_context_takeover: Iff true, client request "no context takeover" feature.
  94. :type request_no_context_takeover: bool
  95. """
  96. if type(accept_no_context_takeover) != bool:
  97. raise Exception("invalid type %s for accept_no_context_takeover" % type(accept_no_context_takeover))
  98. self.accept_no_context_takeover = accept_no_context_takeover
  99. if type(request_no_context_takeover) != bool:
  100. raise Exception("invalid type %s for request_no_context_takeover" % type(request_no_context_takeover))
  101. self.request_no_context_takeover = request_no_context_takeover
  102. def get_extension_string(self):
  103. """
  104. Returns the WebSocket extension configuration string as sent to the server.
  105. :returns: PMCE configuration string.
  106. :rtype: str
  107. """
  108. pmce_string = self.EXTENSION_NAME
  109. if self.accept_no_context_takeover:
  110. pmce_string += "; client_no_context_takeover"
  111. if self.request_no_context_takeover:
  112. pmce_string += "; server_no_context_takeover"
  113. return pmce_string
  114. def __json__(self):
  115. """
  116. Returns a JSON serializable object representation.
  117. :returns: JSON serializable representation.
  118. :rtype: dict
  119. """
  120. return {'extension': self.EXTENSION_NAME,
  121. 'accept_no_context_takeover': self.accept_no_context_takeover,
  122. 'request_no_context_takeover': self.request_no_context_takeover}
  123. def __repr__(self):
  124. """
  125. Returns Python object representation that can be eval'ed to reconstruct the object.
  126. :returns: Python string representation.
  127. :rtype: str
  128. """
  129. return "PerMessageSnappyOffer(accept_no_context_takeover = %s, request_no_context_takeover = %s)" % (self.accept_no_context_takeover, self.request_no_context_takeover)
  130. class PerMessageSnappyOfferAccept(PerMessageCompressOfferAccept, PerMessageSnappyMixin):
  131. """
  132. Set of parameters with which to accept an `permessage-snappy` offer
  133. from a client by a server.
  134. """
  135. def __init__(self,
  136. offer,
  137. request_no_context_takeover=False,
  138. no_context_takeover=None):
  139. """
  140. :param offer: The offer being accepted.
  141. :type offer: Instance of :class:`autobahn.compress.PerMessageSnappyOffer`.
  142. :param request_no_context_takeover: Iff true, server request "no context takeover" feature.
  143. :type request_no_context_takeover: bool
  144. :param no_context_takeover: Override server ("server-to-client direction") context takeover (this must be compatible with offer).
  145. :type no_context_takeover: bool
  146. """
  147. if not isinstance(offer, PerMessageSnappyOffer):
  148. raise Exception("invalid type %s for offer" % type(offer))
  149. self.offer = offer
  150. if type(request_no_context_takeover) != bool:
  151. raise Exception("invalid type %s for request_no_context_takeover" % type(request_no_context_takeover))
  152. if request_no_context_takeover and not offer.accept_no_context_takeover:
  153. raise Exception("invalid value %s for request_no_context_takeover - feature unsupported by client" % request_no_context_takeover)
  154. self.request_no_context_takeover = request_no_context_takeover
  155. if no_context_takeover is not None:
  156. if type(no_context_takeover) != bool:
  157. raise Exception("invalid type %s for no_context_takeover" % type(no_context_takeover))
  158. if offer.request_no_context_takeover and not no_context_takeover:
  159. raise Exception("invalid value %s for no_context_takeover - client requested feature" % no_context_takeover)
  160. self.no_context_takeover = no_context_takeover
  161. def get_extension_string(self):
  162. """
  163. Returns the WebSocket extension configuration string as sent to the server.
  164. :returns: PMCE configuration string.
  165. :rtype: str
  166. """
  167. pmce_string = self.EXTENSION_NAME
  168. if self.offer.request_no_context_takeover:
  169. pmce_string += "; server_no_context_takeover"
  170. if self.request_no_context_takeover:
  171. pmce_string += "; client_no_context_takeover"
  172. return pmce_string
  173. def __json__(self):
  174. """
  175. Returns a JSON serializable object representation.
  176. :returns: JSON serializable representation.
  177. :rtype: dict
  178. """
  179. return {'extension': self.EXTENSION_NAME,
  180. 'offer': self.offer.__json__(),
  181. 'request_no_context_takeover': self.request_no_context_takeover,
  182. 'no_context_takeover': self.no_context_takeover}
  183. def __repr__(self):
  184. """
  185. Returns Python object representation that can be eval'ed to reconstruct the object.
  186. :returns: Python string representation.
  187. :rtype: str
  188. """
  189. 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)
  190. class PerMessageSnappyResponse(PerMessageCompressResponse, PerMessageSnappyMixin):
  191. """
  192. Set of parameters for `permessage-snappy` responded by server.
  193. """
  194. @classmethod
  195. def parse(cls, params):
  196. """
  197. Parses a WebSocket extension response for `permessage-snappy` provided by a server to a client.
  198. :param params: Output from :func:`autobahn.websocket.WebSocketProtocol._parseExtensionsHeader`.
  199. :type params: list
  200. :returns: A new instance of :class:`autobahn.compress.PerMessageSnappyResponse`.
  201. :rtype: obj
  202. """
  203. client_no_context_takeover = False
  204. server_no_context_takeover = False
  205. for p in params:
  206. if len(params[p]) > 1:
  207. raise Exception("multiple occurrence of extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  208. val = params[p][0]
  209. if p == 'client_no_context_takeover':
  210. # noinspection PySimplifyBooleanCheck
  211. if val is not True:
  212. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  213. else:
  214. client_no_context_takeover = True
  215. elif p == 'server_no_context_takeover':
  216. # noinspection PySimplifyBooleanCheck
  217. if val is not True:
  218. raise Exception("illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME))
  219. else:
  220. server_no_context_takeover = True
  221. else:
  222. raise Exception("illegal extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME))
  223. response = cls(client_no_context_takeover,
  224. server_no_context_takeover)
  225. return response
  226. def __init__(self,
  227. client_no_context_takeover,
  228. server_no_context_takeover):
  229. self.client_no_context_takeover = client_no_context_takeover
  230. self.server_no_context_takeover = server_no_context_takeover
  231. def __json__(self):
  232. """
  233. Returns a JSON serializable object representation.
  234. :returns: JSON serializable representation.
  235. :rtype: dict
  236. """
  237. return {'extension': self.EXTENSION_NAME,
  238. 'client_no_context_takeover': self.client_no_context_takeover,
  239. 'server_no_context_takeover': self.server_no_context_takeover}
  240. def __repr__(self):
  241. """
  242. Returns Python object representation that can be eval'ed to reconstruct the object.
  243. :returns: Python string representation.
  244. :rtype: str
  245. """
  246. return "PerMessageSnappyResponse(client_no_context_takeover = %s, server_no_context_takeover = %s)" % (self.client_no_context_takeover, self.server_no_context_takeover)
  247. class PerMessageSnappyResponseAccept(PerMessageCompressResponseAccept, PerMessageSnappyMixin):
  248. """
  249. Set of parameters with which to accept an `permessage-snappy` response
  250. from a server by a client.
  251. """
  252. def __init__(self,
  253. response,
  254. no_context_takeover=None):
  255. """
  256. :param response: The response being accepted.
  257. :type response: Instance of :class:`autobahn.compress.PerMessageSnappyResponse`.
  258. :param no_context_takeover: Override client ("client-to-server direction") context takeover (this must be compatible with response).
  259. :type no_context_takeover: bool
  260. """
  261. if not isinstance(response, PerMessageSnappyResponse):
  262. raise Exception("invalid type %s for response" % type(response))
  263. self.response = response
  264. if no_context_takeover is not None:
  265. if type(no_context_takeover) != bool:
  266. raise Exception("invalid type %s for no_context_takeover" % type(no_context_takeover))
  267. if response.client_no_context_takeover and not no_context_takeover:
  268. raise Exception("invalid value %s for no_context_takeover - server requested feature" % no_context_takeover)
  269. self.no_context_takeover = no_context_takeover
  270. def __json__(self):
  271. """
  272. Returns a JSON serializable object representation.
  273. :returns: JSON serializable representation.
  274. :rtype: dict
  275. """
  276. return {'extension': self.EXTENSION_NAME,
  277. 'response': self.response.__json__(),
  278. 'no_context_takeover': self.no_context_takeover}
  279. def __repr__(self):
  280. """
  281. Returns Python object representation that can be eval'ed to reconstruct the object.
  282. :returns: Python string representation.
  283. :rtype: str
  284. """
  285. return "PerMessageSnappyResponseAccept(response = %s, no_context_takeover = %s)" % (self.response.__repr__(), self.no_context_takeover)
  286. class PerMessageSnappy(PerMessageCompress, PerMessageSnappyMixin):
  287. """
  288. `permessage-snappy` WebSocket extension processor.
  289. """
  290. @classmethod
  291. def create_from_response_accept(cls, is_server, accept):
  292. pmce = cls(is_server,
  293. accept.response.server_no_context_takeover,
  294. accept.no_context_takeover if accept.no_context_takeover is not None else accept.response.client_no_context_takeover)
  295. return pmce
  296. @classmethod
  297. def create_from_offer_accept(cls, is_server, accept):
  298. pmce = cls(is_server,
  299. accept.no_context_takeover if accept.no_context_takeover is not None else accept.offer.request_no_context_takeover,
  300. accept.request_no_context_takeover)
  301. return pmce
  302. def __init__(self,
  303. is_server,
  304. server_no_context_takeover,
  305. client_no_context_takeover):
  306. self._is_server = is_server
  307. self.server_no_context_takeover = server_no_context_takeover
  308. self.client_no_context_takeover = client_no_context_takeover
  309. self._compressor = None
  310. self._decompressor = None
  311. def __json__(self):
  312. return {'extension': self.EXTENSION_NAME,
  313. 'server_no_context_takeover': self.server_no_context_takeover,
  314. 'client_no_context_takeover': self.client_no_context_takeover}
  315. def __repr__(self):
  316. 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)
  317. def start_compress_message(self):
  318. if self._is_server:
  319. if self._compressor is None or self.server_no_context_takeover:
  320. self._compressor = snappy.StreamCompressor()
  321. else:
  322. if self._compressor is None or self.client_no_context_takeover:
  323. self._compressor = snappy.StreamCompressor()
  324. def compress_message_data(self, data):
  325. return self._compressor.add_chunk(data)
  326. def end_compress_message(self):
  327. return b""
  328. def start_decompress_message(self):
  329. if self._is_server:
  330. if self._decompressor is None or self.client_no_context_takeover:
  331. self._decompressor = snappy.StreamDecompressor()
  332. else:
  333. if self._decompressor is None or self.server_no_context_takeover:
  334. self._decompressor = snappy.StreamDecompressor()
  335. def decompress_message_data(self, data):
  336. return self._decompressor.decompress(data)
  337. def end_decompress_message(self):
  338. pass