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.

permessage_deflate.py 24KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. from __future__ import annotations
  2. import dataclasses
  3. import zlib
  4. from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
  5. from .. import exceptions, frames
  6. from ..typing import ExtensionName, ExtensionParameter
  7. from .base import ClientExtensionFactory, Extension, ServerExtensionFactory
  8. __all__ = [
  9. "PerMessageDeflate",
  10. "ClientPerMessageDeflateFactory",
  11. "enable_client_permessage_deflate",
  12. "ServerPerMessageDeflateFactory",
  13. "enable_server_permessage_deflate",
  14. ]
  15. _EMPTY_UNCOMPRESSED_BLOCK = b"\x00\x00\xff\xff"
  16. _MAX_WINDOW_BITS_VALUES = [str(bits) for bits in range(8, 16)]
  17. class PerMessageDeflate(Extension):
  18. """
  19. Per-Message Deflate extension.
  20. """
  21. name = ExtensionName("permessage-deflate")
  22. def __init__(
  23. self,
  24. remote_no_context_takeover: bool,
  25. local_no_context_takeover: bool,
  26. remote_max_window_bits: int,
  27. local_max_window_bits: int,
  28. compress_settings: Optional[Dict[Any, Any]] = None,
  29. ) -> None:
  30. """
  31. Configure the Per-Message Deflate extension.
  32. """
  33. if compress_settings is None:
  34. compress_settings = {}
  35. assert remote_no_context_takeover in [False, True]
  36. assert local_no_context_takeover in [False, True]
  37. assert 8 <= remote_max_window_bits <= 15
  38. assert 8 <= local_max_window_bits <= 15
  39. assert "wbits" not in compress_settings
  40. self.remote_no_context_takeover = remote_no_context_takeover
  41. self.local_no_context_takeover = local_no_context_takeover
  42. self.remote_max_window_bits = remote_max_window_bits
  43. self.local_max_window_bits = local_max_window_bits
  44. self.compress_settings = compress_settings
  45. if not self.remote_no_context_takeover:
  46. self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits)
  47. if not self.local_no_context_takeover:
  48. self.encoder = zlib.compressobj(
  49. wbits=-self.local_max_window_bits, **self.compress_settings
  50. )
  51. # To handle continuation frames properly, we must keep track of
  52. # whether that initial frame was encoded.
  53. self.decode_cont_data = False
  54. # There's no need for self.encode_cont_data because we always encode
  55. # outgoing frames, so it would always be True.
  56. def __repr__(self) -> str:
  57. return (
  58. f"PerMessageDeflate("
  59. f"remote_no_context_takeover={self.remote_no_context_takeover}, "
  60. f"local_no_context_takeover={self.local_no_context_takeover}, "
  61. f"remote_max_window_bits={self.remote_max_window_bits}, "
  62. f"local_max_window_bits={self.local_max_window_bits})"
  63. )
  64. def decode(
  65. self,
  66. frame: frames.Frame,
  67. *,
  68. max_size: Optional[int] = None,
  69. ) -> frames.Frame:
  70. """
  71. Decode an incoming frame.
  72. """
  73. # Skip control frames.
  74. if frame.opcode in frames.CTRL_OPCODES:
  75. return frame
  76. # Handle continuation data frames:
  77. # - skip if the message isn't encoded
  78. # - reset "decode continuation data" flag if it's a final frame
  79. if frame.opcode is frames.OP_CONT:
  80. if not self.decode_cont_data:
  81. return frame
  82. if frame.fin:
  83. self.decode_cont_data = False
  84. # Handle text and binary data frames:
  85. # - skip if the message isn't encoded
  86. # - unset the rsv1 flag on the first frame of a compressed message
  87. # - set "decode continuation data" flag if it's a non-final frame
  88. else:
  89. if not frame.rsv1:
  90. return frame
  91. frame = dataclasses.replace(frame, rsv1=False)
  92. if not frame.fin:
  93. self.decode_cont_data = True
  94. # Re-initialize per-message decoder.
  95. if self.remote_no_context_takeover:
  96. self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits)
  97. # Uncompress data. Protect against zip bombs by preventing zlib from
  98. # decompressing more than max_length bytes (except when the limit is
  99. # disabled with max_size = None).
  100. data = frame.data
  101. if frame.fin:
  102. data += _EMPTY_UNCOMPRESSED_BLOCK
  103. max_length = 0 if max_size is None else max_size
  104. try:
  105. data = self.decoder.decompress(data, max_length)
  106. except zlib.error as exc:
  107. raise exceptions.ProtocolError("decompression failed") from exc
  108. if self.decoder.unconsumed_tail:
  109. raise exceptions.PayloadTooBig(f"over size limit (? > {max_size} bytes)")
  110. # Allow garbage collection of the decoder if it won't be reused.
  111. if frame.fin and self.remote_no_context_takeover:
  112. del self.decoder
  113. return dataclasses.replace(frame, data=data)
  114. def encode(self, frame: frames.Frame) -> frames.Frame:
  115. """
  116. Encode an outgoing frame.
  117. """
  118. # Skip control frames.
  119. if frame.opcode in frames.CTRL_OPCODES:
  120. return frame
  121. # Since we always encode messages, there's no "encode continuation
  122. # data" flag similar to "decode continuation data" at this time.
  123. if frame.opcode is not frames.OP_CONT:
  124. # Set the rsv1 flag on the first frame of a compressed message.
  125. frame = dataclasses.replace(frame, rsv1=True)
  126. # Re-initialize per-message decoder.
  127. if self.local_no_context_takeover:
  128. self.encoder = zlib.compressobj(
  129. wbits=-self.local_max_window_bits, **self.compress_settings
  130. )
  131. # Compress data.
  132. data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH)
  133. if frame.fin and data.endswith(_EMPTY_UNCOMPRESSED_BLOCK):
  134. data = data[:-4]
  135. # Allow garbage collection of the encoder if it won't be reused.
  136. if frame.fin and self.local_no_context_takeover:
  137. del self.encoder
  138. return dataclasses.replace(frame, data=data)
  139. def _build_parameters(
  140. server_no_context_takeover: bool,
  141. client_no_context_takeover: bool,
  142. server_max_window_bits: Optional[int],
  143. client_max_window_bits: Optional[Union[int, bool]],
  144. ) -> List[ExtensionParameter]:
  145. """
  146. Build a list of ``(name, value)`` pairs for some compression parameters.
  147. """
  148. params: List[ExtensionParameter] = []
  149. if server_no_context_takeover:
  150. params.append(("server_no_context_takeover", None))
  151. if client_no_context_takeover:
  152. params.append(("client_no_context_takeover", None))
  153. if server_max_window_bits:
  154. params.append(("server_max_window_bits", str(server_max_window_bits)))
  155. if client_max_window_bits is True: # only in handshake requests
  156. params.append(("client_max_window_bits", None))
  157. elif client_max_window_bits:
  158. params.append(("client_max_window_bits", str(client_max_window_bits)))
  159. return params
  160. def _extract_parameters(
  161. params: Sequence[ExtensionParameter], *, is_server: bool
  162. ) -> Tuple[bool, bool, Optional[int], Optional[Union[int, bool]]]:
  163. """
  164. Extract compression parameters from a list of ``(name, value)`` pairs.
  165. If ``is_server`` is :obj:`True`, ``client_max_window_bits`` may be
  166. provided without a value. This is only allowed in handshake requests.
  167. """
  168. server_no_context_takeover: bool = False
  169. client_no_context_takeover: bool = False
  170. server_max_window_bits: Optional[int] = None
  171. client_max_window_bits: Optional[Union[int, bool]] = None
  172. for name, value in params:
  173. if name == "server_no_context_takeover":
  174. if server_no_context_takeover:
  175. raise exceptions.DuplicateParameter(name)
  176. if value is None:
  177. server_no_context_takeover = True
  178. else:
  179. raise exceptions.InvalidParameterValue(name, value)
  180. elif name == "client_no_context_takeover":
  181. if client_no_context_takeover:
  182. raise exceptions.DuplicateParameter(name)
  183. if value is None:
  184. client_no_context_takeover = True
  185. else:
  186. raise exceptions.InvalidParameterValue(name, value)
  187. elif name == "server_max_window_bits":
  188. if server_max_window_bits is not None:
  189. raise exceptions.DuplicateParameter(name)
  190. if value in _MAX_WINDOW_BITS_VALUES:
  191. server_max_window_bits = int(value)
  192. else:
  193. raise exceptions.InvalidParameterValue(name, value)
  194. elif name == "client_max_window_bits":
  195. if client_max_window_bits is not None:
  196. raise exceptions.DuplicateParameter(name)
  197. if is_server and value is None: # only in handshake requests
  198. client_max_window_bits = True
  199. elif value in _MAX_WINDOW_BITS_VALUES:
  200. client_max_window_bits = int(value)
  201. else:
  202. raise exceptions.InvalidParameterValue(name, value)
  203. else:
  204. raise exceptions.InvalidParameterName(name)
  205. return (
  206. server_no_context_takeover,
  207. client_no_context_takeover,
  208. server_max_window_bits,
  209. client_max_window_bits,
  210. )
  211. class ClientPerMessageDeflateFactory(ClientExtensionFactory):
  212. """
  213. Client-side extension factory for the Per-Message Deflate extension.
  214. Parameters behave as described in `section 7.1 of RFC 7692`_.
  215. .. _section 7.1 of RFC 7692: https://www.rfc-editor.org/rfc/rfc7692.html#section-7.1
  216. Set them to :obj:`True` to include them in the negotiation offer without a
  217. value or to an integer value to include them with this value.
  218. Args:
  219. server_no_context_takeover: prevent server from using context takeover.
  220. client_no_context_takeover: prevent client from using context takeover.
  221. server_max_window_bits: maximum size of the server's LZ77 sliding window
  222. in bits, between 8 and 15.
  223. client_max_window_bits: maximum size of the client's LZ77 sliding window
  224. in bits, between 8 and 15, or :obj:`True` to indicate support without
  225. setting a limit.
  226. compress_settings: additional keyword arguments for :func:`zlib.compressobj`,
  227. excluding ``wbits``.
  228. """
  229. name = ExtensionName("permessage-deflate")
  230. def __init__(
  231. self,
  232. server_no_context_takeover: bool = False,
  233. client_no_context_takeover: bool = False,
  234. server_max_window_bits: Optional[int] = None,
  235. client_max_window_bits: Optional[Union[int, bool]] = True,
  236. compress_settings: Optional[Dict[str, Any]] = None,
  237. ) -> None:
  238. """
  239. Configure the Per-Message Deflate extension factory.
  240. """
  241. if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15):
  242. raise ValueError("server_max_window_bits must be between 8 and 15")
  243. if not (
  244. client_max_window_bits is None
  245. or client_max_window_bits is True
  246. or 8 <= client_max_window_bits <= 15
  247. ):
  248. raise ValueError("client_max_window_bits must be between 8 and 15")
  249. if compress_settings is not None and "wbits" in compress_settings:
  250. raise ValueError(
  251. "compress_settings must not include wbits, "
  252. "set client_max_window_bits instead"
  253. )
  254. self.server_no_context_takeover = server_no_context_takeover
  255. self.client_no_context_takeover = client_no_context_takeover
  256. self.server_max_window_bits = server_max_window_bits
  257. self.client_max_window_bits = client_max_window_bits
  258. self.compress_settings = compress_settings
  259. def get_request_params(self) -> List[ExtensionParameter]:
  260. """
  261. Build request parameters.
  262. """
  263. return _build_parameters(
  264. self.server_no_context_takeover,
  265. self.client_no_context_takeover,
  266. self.server_max_window_bits,
  267. self.client_max_window_bits,
  268. )
  269. def process_response_params(
  270. self,
  271. params: Sequence[ExtensionParameter],
  272. accepted_extensions: Sequence[Extension],
  273. ) -> PerMessageDeflate:
  274. """
  275. Process response parameters.
  276. Return an extension instance.
  277. """
  278. if any(other.name == self.name for other in accepted_extensions):
  279. raise exceptions.NegotiationError(f"received duplicate {self.name}")
  280. # Request parameters are available in instance variables.
  281. # Load response parameters in local variables.
  282. (
  283. server_no_context_takeover,
  284. client_no_context_takeover,
  285. server_max_window_bits,
  286. client_max_window_bits,
  287. ) = _extract_parameters(params, is_server=False)
  288. # After comparing the request and the response, the final
  289. # configuration must be available in the local variables.
  290. # server_no_context_takeover
  291. #
  292. # Req. Resp. Result
  293. # ------ ------ --------------------------------------------------
  294. # False False False
  295. # False True True
  296. # True False Error!
  297. # True True True
  298. if self.server_no_context_takeover:
  299. if not server_no_context_takeover:
  300. raise exceptions.NegotiationError("expected server_no_context_takeover")
  301. # client_no_context_takeover
  302. #
  303. # Req. Resp. Result
  304. # ------ ------ --------------------------------------------------
  305. # False False False
  306. # False True True
  307. # True False True - must change value
  308. # True True True
  309. if self.client_no_context_takeover:
  310. if not client_no_context_takeover:
  311. client_no_context_takeover = True
  312. # server_max_window_bits
  313. # Req. Resp. Result
  314. # ------ ------ --------------------------------------------------
  315. # None None None
  316. # None 8≤M≤15 M
  317. # 8≤N≤15 None Error!
  318. # 8≤N≤15 8≤M≤N M
  319. # 8≤N≤15 N<M≤15 Error!
  320. if self.server_max_window_bits is None:
  321. pass
  322. else:
  323. if server_max_window_bits is None:
  324. raise exceptions.NegotiationError("expected server_max_window_bits")
  325. elif server_max_window_bits > self.server_max_window_bits:
  326. raise exceptions.NegotiationError("unsupported server_max_window_bits")
  327. # client_max_window_bits
  328. # Req. Resp. Result
  329. # ------ ------ --------------------------------------------------
  330. # None None None
  331. # None 8≤M≤15 Error!
  332. # True None None
  333. # True 8≤M≤15 M
  334. # 8≤N≤15 None N - must change value
  335. # 8≤N≤15 8≤M≤N M
  336. # 8≤N≤15 N<M≤15 Error!
  337. if self.client_max_window_bits is None:
  338. if client_max_window_bits is not None:
  339. raise exceptions.NegotiationError("unexpected client_max_window_bits")
  340. elif self.client_max_window_bits is True:
  341. pass
  342. else:
  343. if client_max_window_bits is None:
  344. client_max_window_bits = self.client_max_window_bits
  345. elif client_max_window_bits > self.client_max_window_bits:
  346. raise exceptions.NegotiationError("unsupported client_max_window_bits")
  347. return PerMessageDeflate(
  348. server_no_context_takeover, # remote_no_context_takeover
  349. client_no_context_takeover, # local_no_context_takeover
  350. server_max_window_bits or 15, # remote_max_window_bits
  351. client_max_window_bits or 15, # local_max_window_bits
  352. self.compress_settings,
  353. )
  354. def enable_client_permessage_deflate(
  355. extensions: Optional[Sequence[ClientExtensionFactory]],
  356. ) -> Sequence[ClientExtensionFactory]:
  357. """
  358. Enable Per-Message Deflate with default settings in client extensions.
  359. If the extension is already present, perhaps with non-default settings,
  360. the configuration isn't changed.
  361. """
  362. if extensions is None:
  363. extensions = []
  364. if not any(
  365. extension_factory.name == ClientPerMessageDeflateFactory.name
  366. for extension_factory in extensions
  367. ):
  368. extensions = list(extensions) + [
  369. ClientPerMessageDeflateFactory(
  370. compress_settings={"memLevel": 5},
  371. )
  372. ]
  373. return extensions
  374. class ServerPerMessageDeflateFactory(ServerExtensionFactory):
  375. """
  376. Server-side extension factory for the Per-Message Deflate extension.
  377. Parameters behave as described in `section 7.1 of RFC 7692`_.
  378. .. _section 7.1 of RFC 7692: https://www.rfc-editor.org/rfc/rfc7692.html#section-7.1
  379. Set them to :obj:`True` to include them in the negotiation offer without a
  380. value or to an integer value to include them with this value.
  381. Args:
  382. server_no_context_takeover: prevent server from using context takeover.
  383. client_no_context_takeover: prevent client from using context takeover.
  384. server_max_window_bits: maximum size of the server's LZ77 sliding window
  385. in bits, between 8 and 15.
  386. client_max_window_bits: maximum size of the client's LZ77 sliding window
  387. in bits, between 8 and 15.
  388. compress_settings: additional keyword arguments for :func:`zlib.compressobj`,
  389. excluding ``wbits``.
  390. require_client_max_window_bits: do not enable compression at all if
  391. client doesn't advertise support for ``client_max_window_bits``;
  392. the default behavior is to enable compression without enforcing
  393. ``client_max_window_bits``.
  394. """
  395. name = ExtensionName("permessage-deflate")
  396. def __init__(
  397. self,
  398. server_no_context_takeover: bool = False,
  399. client_no_context_takeover: bool = False,
  400. server_max_window_bits: Optional[int] = None,
  401. client_max_window_bits: Optional[int] = None,
  402. compress_settings: Optional[Dict[str, Any]] = None,
  403. require_client_max_window_bits: bool = False,
  404. ) -> None:
  405. """
  406. Configure the Per-Message Deflate extension factory.
  407. """
  408. if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15):
  409. raise ValueError("server_max_window_bits must be between 8 and 15")
  410. if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15):
  411. raise ValueError("client_max_window_bits must be between 8 and 15")
  412. if compress_settings is not None and "wbits" in compress_settings:
  413. raise ValueError(
  414. "compress_settings must not include wbits, "
  415. "set server_max_window_bits instead"
  416. )
  417. if client_max_window_bits is None and require_client_max_window_bits:
  418. raise ValueError(
  419. "require_client_max_window_bits is enabled, "
  420. "but client_max_window_bits isn't configured"
  421. )
  422. self.server_no_context_takeover = server_no_context_takeover
  423. self.client_no_context_takeover = client_no_context_takeover
  424. self.server_max_window_bits = server_max_window_bits
  425. self.client_max_window_bits = client_max_window_bits
  426. self.compress_settings = compress_settings
  427. self.require_client_max_window_bits = require_client_max_window_bits
  428. def process_request_params(
  429. self,
  430. params: Sequence[ExtensionParameter],
  431. accepted_extensions: Sequence[Extension],
  432. ) -> Tuple[List[ExtensionParameter], PerMessageDeflate]:
  433. """
  434. Process request parameters.
  435. Return response params and an extension instance.
  436. """
  437. if any(other.name == self.name for other in accepted_extensions):
  438. raise exceptions.NegotiationError(f"skipped duplicate {self.name}")
  439. # Load request parameters in local variables.
  440. (
  441. server_no_context_takeover,
  442. client_no_context_takeover,
  443. server_max_window_bits,
  444. client_max_window_bits,
  445. ) = _extract_parameters(params, is_server=True)
  446. # Configuration parameters are available in instance variables.
  447. # After comparing the request and the configuration, the response must
  448. # be available in the local variables.
  449. # server_no_context_takeover
  450. #
  451. # Config Req. Resp.
  452. # ------ ------ --------------------------------------------------
  453. # False False False
  454. # False True True
  455. # True False True - must change value to True
  456. # True True True
  457. if self.server_no_context_takeover:
  458. if not server_no_context_takeover:
  459. server_no_context_takeover = True
  460. # client_no_context_takeover
  461. #
  462. # Config Req. Resp.
  463. # ------ ------ --------------------------------------------------
  464. # False False False
  465. # False True True (or False)
  466. # True False True - must change value to True
  467. # True True True (or False)
  468. if self.client_no_context_takeover:
  469. if not client_no_context_takeover:
  470. client_no_context_takeover = True
  471. # server_max_window_bits
  472. # Config Req. Resp.
  473. # ------ ------ --------------------------------------------------
  474. # None None None
  475. # None 8≤M≤15 M
  476. # 8≤N≤15 None N - must change value
  477. # 8≤N≤15 8≤M≤N M
  478. # 8≤N≤15 N<M≤15 N - must change value
  479. if self.server_max_window_bits is None:
  480. pass
  481. else:
  482. if server_max_window_bits is None:
  483. server_max_window_bits = self.server_max_window_bits
  484. elif server_max_window_bits > self.server_max_window_bits:
  485. server_max_window_bits = self.server_max_window_bits
  486. # client_max_window_bits
  487. # Config Req. Resp.
  488. # ------ ------ --------------------------------------------------
  489. # None None None
  490. # None True None - must change value
  491. # None 8≤M≤15 M (or None)
  492. # 8≤N≤15 None None or Error!
  493. # 8≤N≤15 True N - must change value
  494. # 8≤N≤15 8≤M≤N M (or None)
  495. # 8≤N≤15 N<M≤15 N
  496. if self.client_max_window_bits is None:
  497. if client_max_window_bits is True:
  498. client_max_window_bits = self.client_max_window_bits
  499. else:
  500. if client_max_window_bits is None:
  501. if self.require_client_max_window_bits:
  502. raise exceptions.NegotiationError("required client_max_window_bits")
  503. elif client_max_window_bits is True:
  504. client_max_window_bits = self.client_max_window_bits
  505. elif self.client_max_window_bits < client_max_window_bits:
  506. client_max_window_bits = self.client_max_window_bits
  507. return (
  508. _build_parameters(
  509. server_no_context_takeover,
  510. client_no_context_takeover,
  511. server_max_window_bits,
  512. client_max_window_bits,
  513. ),
  514. PerMessageDeflate(
  515. client_no_context_takeover, # remote_no_context_takeover
  516. server_no_context_takeover, # local_no_context_takeover
  517. client_max_window_bits or 15, # remote_max_window_bits
  518. server_max_window_bits or 15, # local_max_window_bits
  519. self.compress_settings,
  520. ),
  521. )
  522. def enable_server_permessage_deflate(
  523. extensions: Optional[Sequence[ServerExtensionFactory]],
  524. ) -> Sequence[ServerExtensionFactory]:
  525. """
  526. Enable Per-Message Deflate with default settings in server extensions.
  527. If the extension is already present, perhaps with non-default settings,
  528. the configuration isn't changed.
  529. """
  530. if extensions is None:
  531. extensions = []
  532. if not any(
  533. ext_factory.name == ServerPerMessageDeflateFactory.name
  534. for ext_factory in extensions
  535. ):
  536. extensions = list(extensions) + [
  537. ServerPerMessageDeflateFactory(
  538. server_max_window_bits=12,
  539. client_max_window_bits=12,
  540. compress_settings={"memLevel": 5},
  541. )
  542. ]
  543. return extensions