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_bzip2.py 18KB

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