frames.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. from __future__ import annotations
  2. import dataclasses
  3. import enum
  4. import io
  5. import os
  6. import re
  7. import secrets
  8. import struct
  9. from collections.abc import Generator, Sequence
  10. from typing import Callable, Self
  11. from .exceptions import PayloadTooBig, ProtocolError
  12. from .typing import BytesLike
  13. try:
  14. from .speedups import apply_mask
  15. except ImportError:
  16. from .utils import apply_mask
  17. __all__ = [
  18. "Opcode",
  19. "CloseCode",
  20. "Frame",
  21. "Close",
  22. ]
  23. is_space_or_printable_ascii = re.compile(rb"[\x09-\x0D\x20-\x7E]*").fullmatch
  24. class Opcode(enum.IntEnum):
  25. """Opcode values for WebSocket frames."""
  26. CONT, TEXT, BINARY = 0x00, 0x01, 0x02
  27. CLOSE, PING, PONG = 0x08, 0x09, 0x0A
  28. CONT = Opcode.CONT
  29. TEXT = Opcode.TEXT
  30. BINARY = Opcode.BINARY
  31. CLOSE = Opcode.CLOSE
  32. PING = Opcode.PING
  33. PONG = Opcode.PONG
  34. DATA_OPCODES = CONT, TEXT, BINARY
  35. CTRL_OPCODES = CLOSE, PING, PONG
  36. class CloseCode(enum.IntEnum):
  37. """Close code values for WebSocket close frames."""
  38. NORMAL_CLOSURE = 1000
  39. GOING_AWAY = 1001
  40. PROTOCOL_ERROR = 1002
  41. UNSUPPORTED_DATA = 1003
  42. # 1004 is reserved
  43. NO_STATUS_RCVD = 1005
  44. ABNORMAL_CLOSURE = 1006
  45. INVALID_DATA = 1007
  46. POLICY_VIOLATION = 1008
  47. MESSAGE_TOO_BIG = 1009
  48. MANDATORY_EXTENSION = 1010
  49. INTERNAL_ERROR = 1011
  50. SERVICE_RESTART = 1012
  51. TRY_AGAIN_LATER = 1013
  52. BAD_GATEWAY = 1014
  53. TLS_HANDSHAKE = 1015
  54. # See https://www.iana.org/assignments/websocket/websocket.xhtml
  55. CLOSE_CODE_EXPLANATIONS: dict[int, str] = {
  56. CloseCode.NORMAL_CLOSURE: "OK",
  57. CloseCode.GOING_AWAY: "going away",
  58. CloseCode.PROTOCOL_ERROR: "protocol error",
  59. CloseCode.UNSUPPORTED_DATA: "unsupported data",
  60. CloseCode.NO_STATUS_RCVD: "no status received [internal]",
  61. CloseCode.ABNORMAL_CLOSURE: "abnormal closure [internal]",
  62. CloseCode.INVALID_DATA: "invalid frame payload data",
  63. CloseCode.POLICY_VIOLATION: "policy violation",
  64. CloseCode.MESSAGE_TOO_BIG: "message too big",
  65. CloseCode.MANDATORY_EXTENSION: "mandatory extension",
  66. CloseCode.INTERNAL_ERROR: "internal error",
  67. CloseCode.SERVICE_RESTART: "service restart",
  68. CloseCode.TRY_AGAIN_LATER: "try again later",
  69. CloseCode.BAD_GATEWAY: "bad gateway",
  70. CloseCode.TLS_HANDSHAKE: "TLS handshake failure [internal]",
  71. }
  72. # Close code that are allowed in a close frame.
  73. # Using a set optimizes `code in EXTERNAL_CLOSE_CODES`.
  74. EXTERNAL_CLOSE_CODES = {
  75. CloseCode.NORMAL_CLOSURE,
  76. CloseCode.GOING_AWAY,
  77. CloseCode.PROTOCOL_ERROR,
  78. CloseCode.UNSUPPORTED_DATA,
  79. CloseCode.INVALID_DATA,
  80. CloseCode.POLICY_VIOLATION,
  81. CloseCode.MESSAGE_TOO_BIG,
  82. CloseCode.MANDATORY_EXTENSION,
  83. CloseCode.INTERNAL_ERROR,
  84. CloseCode.SERVICE_RESTART,
  85. CloseCode.TRY_AGAIN_LATER,
  86. CloseCode.BAD_GATEWAY,
  87. }
  88. OK_CLOSE_CODES = {
  89. CloseCode.NORMAL_CLOSURE,
  90. CloseCode.GOING_AWAY,
  91. CloseCode.NO_STATUS_RCVD,
  92. }
  93. @dataclasses.dataclass
  94. class Frame:
  95. """
  96. WebSocket frame.
  97. Attributes:
  98. opcode: Opcode.
  99. data: Payload data.
  100. fin: FIN bit.
  101. rsv1: RSV1 bit.
  102. rsv2: RSV2 bit.
  103. rsv3: RSV3 bit.
  104. Only these fields are needed. The MASK bit, payload length and masking-key
  105. are handled on the fly when parsing and serializing frames.
  106. """
  107. opcode: Opcode
  108. data: BytesLike
  109. fin: bool = True
  110. rsv1: bool = False
  111. rsv2: bool = False
  112. rsv3: bool = False
  113. # Configure if you want to see more in logs. Should be a multiple of 3.
  114. MAX_LOG_SIZE = int(os.environ.get("WEBSOCKETS_MAX_LOG_SIZE", "75"))
  115. DEFAULT_IS_TEXT = {TEXT: True, BINARY: False, CLOSE: True}
  116. def __str__(self) -> str:
  117. """
  118. Return a human-readable representation of a frame.
  119. This function is intended for logging and debugging. It doesn't aim to
  120. support round-tripping because payloads can be too long for displaying
  121. conveniently. Instead, it shows the beginning and the end. It's robust
  122. to incorrect data.
  123. It attempts to decode UTF-8 in data frames, even in binary frames,
  124. because those frequently contain UTF-8 data.
  125. """
  126. expect_text = self.DEFAULT_IS_TEXT.get(self.opcode)
  127. data_repr, is_text = self._data_repr()
  128. data_type = "" if expect_text == is_text else ("text" if is_text else "binary")
  129. length = f"{len(self.data)} byte{'' if len(self.data) == 1 else 's'}"
  130. non_final = "" if self.fin else "continued"
  131. metadata = ", ".join(filter(None, [data_type, length, non_final]))
  132. return f"{self.opcode.name} {data_repr} [{metadata}]"
  133. def _data_repr(self) -> tuple[str, bool | None]:
  134. """
  135. Return a human-readable representation of the payload.
  136. Also returns whether the payload is text.
  137. The representation is elided to fit ``MAX_LOG_SIZE``.
  138. This is a helper for the __str__ method.
  139. """
  140. data_repr: str = ""
  141. is_text: bool | None = None
  142. if not self.data:
  143. return "''", self.DEFAULT_IS_TEXT.get(self.opcode)
  144. # Close frames: parse close code and reason and display them as text.
  145. # Fall back to binary when the payload is malformed.
  146. if self.opcode is CLOSE:
  147. try:
  148. data_repr = str(Close.parse(self.data))
  149. is_text = True
  150. except (ProtocolError, UnicodeDecodeError):
  151. data_repr = " ".join(f"{byte:02x}" for byte in self.data)
  152. is_text = False
  153. # Control frames: display printable ASCII payloads as text, else binary.
  154. # We could decode UTF-8 payloads, but this causes confusion when random
  155. # 4-bytes binary payloads are accidentally valid UTF-8 sequences.
  156. elif self.opcode in CTRL_OPCODES:
  157. if is_space_or_printable_ascii(self.data):
  158. data_repr = repr(bytes(self.data).decode("ascii"))
  159. is_text = True
  160. else:
  161. data_repr = " ".join(f"{byte:02x}" for byte in self.data)
  162. is_text = False
  163. # Data frames: check whether the payload is UTF-8, regardless of opcode,
  164. # in order to display nicely UTF-8 text in binary frames, and be robust.
  165. # Also support frames fragmented within UTF-8 sequences.
  166. else:
  167. if len(self.data) > 4 * self.MAX_LOG_SIZE:
  168. # Process only the start and end, as the middle will be elided.
  169. # Cast to bytes because self.data could be a memoryview.
  170. data_start = bytes(self.data[: 8 * self.MAX_LOG_SIZE // 3])
  171. data_end = bytes(self.data[-4 * self.MAX_LOG_SIZE // 3 :])
  172. is_text = is_utf8_fragment(
  173. data_start,
  174. must_start_clean=self.opcode != CONT,
  175. ) and is_utf8_fragment(
  176. data_end,
  177. must_end_clean=self.fin,
  178. )
  179. if is_text:
  180. data_repr = repr((data_start + data_end).decode(errors="replace"))
  181. else:
  182. # Cast to bytes because self.data could be a memoryview.
  183. data = bytes(self.data)
  184. is_text = is_utf8_fragment(
  185. data,
  186. must_start_clean=self.opcode != CONT,
  187. must_end_clean=self.fin,
  188. )
  189. if is_text:
  190. data_repr = repr(data.decode(errors="replace"))
  191. # When the payload is text (except perhaps for boundaries), we have
  192. # enough in ``data_repr``. Do the same when the payload is binary.
  193. if not is_text:
  194. binary = self.data
  195. if len(binary) > self.MAX_LOG_SIZE // 3:
  196. cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8
  197. # Encode two dummy bytes to force eliding and adding an ellipsis.
  198. binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]])
  199. data_repr = " ".join(f"{byte:02x}" for byte in binary)
  200. # Elide the middle of the representation to fit the maximum log size.
  201. if len(data_repr) > self.MAX_LOG_SIZE:
  202. cut = self.MAX_LOG_SIZE // 3 - 1 # by default cut = 24
  203. data_repr = data_repr[: 2 * cut] + "..." + data_repr[-cut:]
  204. return data_repr, is_text
  205. @classmethod
  206. def parse(
  207. cls,
  208. read_exact: Callable[[int], Generator[None, None, bytes | bytearray]],
  209. *,
  210. mask: bool,
  211. max_size: int | None = None,
  212. extensions: Sequence[extensions.Extension] | None = None,
  213. ) -> Generator[None, None, Frame]:
  214. """
  215. Parse a WebSocket frame.
  216. This is a generator-based coroutine.
  217. Args:
  218. read_exact: Generator-based coroutine that reads the requested
  219. bytes or raises an exception if there isn't enough data.
  220. mask: Whether the frame should be masked i.e. whether the read
  221. happens on the server side.
  222. max_size: Maximum payload size in bytes.
  223. extensions: List of extensions, applied in reverse order.
  224. Raises:
  225. EOFError: If the connection is closed without a full WebSocket frame.
  226. PayloadTooBig: If the frame's payload size exceeds ``max_size``.
  227. ProtocolError: If the frame contains incorrect values.
  228. """
  229. # Read the header.
  230. data = yield from read_exact(2)
  231. head1, head2 = struct.unpack("!BB", data)
  232. # While not Pythonic, this is marginally faster than calling bool().
  233. fin = True if head1 & 0b10000000 else False
  234. rsv1 = True if head1 & 0b01000000 else False
  235. rsv2 = True if head1 & 0b00100000 else False
  236. rsv3 = True if head1 & 0b00010000 else False
  237. try:
  238. opcode = Opcode(head1 & 0b00001111)
  239. except ValueError as exc:
  240. raise ProtocolError("invalid opcode") from exc
  241. if (True if head2 & 0b10000000 else False) != mask:
  242. raise ProtocolError("incorrect masking")
  243. length = head2 & 0b01111111
  244. if length == 126:
  245. data = yield from read_exact(2)
  246. (length,) = struct.unpack("!H", data)
  247. elif length == 127:
  248. data = yield from read_exact(8)
  249. (length,) = struct.unpack("!Q", data)
  250. if max_size is not None and length > max_size:
  251. raise PayloadTooBig(length, max_size)
  252. if mask:
  253. mask_bytes = yield from read_exact(4)
  254. # Read the data.
  255. data = yield from read_exact(length)
  256. if mask:
  257. data = apply_mask(data, mask_bytes)
  258. frame = cls(opcode, data, fin, rsv1, rsv2, rsv3)
  259. if extensions is None:
  260. extensions = []
  261. for extension in reversed(extensions):
  262. frame = extension.decode(frame, max_size=max_size)
  263. frame.check()
  264. return frame
  265. def serialize(
  266. self,
  267. *,
  268. mask: bool,
  269. extensions: Sequence[extensions.Extension] | None = None,
  270. ) -> bytes:
  271. """
  272. Serialize a WebSocket frame.
  273. Args:
  274. mask: Whether the frame should be masked i.e. whether the write
  275. happens on the client side.
  276. extensions: List of extensions, applied in order.
  277. Raises:
  278. ProtocolError: If the frame contains incorrect values.
  279. """
  280. self.check()
  281. if extensions is None:
  282. extensions = []
  283. for extension in extensions:
  284. self = extension.encode(self)
  285. output = io.BytesIO()
  286. # Prepare the header.
  287. head1 = (
  288. (0b10000000 if self.fin else 0)
  289. | (0b01000000 if self.rsv1 else 0)
  290. | (0b00100000 if self.rsv2 else 0)
  291. | (0b00010000 if self.rsv3 else 0)
  292. | self.opcode
  293. )
  294. head2 = 0b10000000 if mask else 0
  295. length = len(self.data)
  296. if length < 126:
  297. output.write(struct.pack("!BB", head1, head2 | length))
  298. elif length < 65536:
  299. output.write(struct.pack("!BBH", head1, head2 | 126, length))
  300. else:
  301. output.write(struct.pack("!BBQ", head1, head2 | 127, length))
  302. if mask:
  303. mask_bytes = secrets.token_bytes(4)
  304. output.write(mask_bytes)
  305. # Prepare the data.
  306. data: BytesLike
  307. if mask:
  308. data = apply_mask(self.data, mask_bytes)
  309. else:
  310. data = self.data
  311. output.write(data)
  312. return output.getvalue()
  313. def check(self) -> None:
  314. """
  315. Check that reserved bits and opcode have acceptable values.
  316. Raises:
  317. ProtocolError: If a reserved bit or the opcode is invalid.
  318. """
  319. if self.rsv1 or self.rsv2 or self.rsv3:
  320. raise ProtocolError("reserved bits must be 0")
  321. if self.opcode in CTRL_OPCODES:
  322. if len(self.data) > 125:
  323. raise ProtocolError("control frame too long")
  324. if not self.fin:
  325. raise ProtocolError("fragmented control frame")
  326. @dataclasses.dataclass
  327. class Close:
  328. """
  329. Code and reason for WebSocket close frames.
  330. Attributes:
  331. code: Close code.
  332. reason: Close reason.
  333. """
  334. code: CloseCode | int
  335. reason: str
  336. def __str__(self) -> str:
  337. """
  338. Return a human-readable representation of a close code and reason.
  339. """
  340. if 3000 <= self.code < 4000:
  341. explanation = "registered"
  342. elif 4000 <= self.code < 5000:
  343. explanation = "private use"
  344. else:
  345. explanation = CLOSE_CODE_EXPLANATIONS.get(self.code, "unknown")
  346. result = f"{self.code} ({explanation})"
  347. if self.reason:
  348. result = f"{result} {self.reason}"
  349. return result
  350. @classmethod
  351. def parse(cls, data: BytesLike) -> Self:
  352. """
  353. Parse the payload of a close frame.
  354. Args:
  355. data: Payload of the close frame.
  356. Raises:
  357. ProtocolError: If data is ill-formed.
  358. UnicodeDecodeError: If the reason isn't valid UTF-8.
  359. """
  360. if isinstance(data, memoryview):
  361. raise AssertionError("only compressed outgoing frames use memoryview")
  362. if len(data) >= 2:
  363. (code,) = struct.unpack("!H", data[:2])
  364. reason = data[2:].decode()
  365. close = cls(code, reason)
  366. close.check()
  367. return close
  368. elif len(data) == 0:
  369. return cls(CloseCode.NO_STATUS_RCVD, "")
  370. else:
  371. raise ProtocolError("close frame too short")
  372. def serialize(self) -> bytes:
  373. """
  374. Serialize the payload of a close frame.
  375. """
  376. self.check()
  377. return struct.pack("!H", self.code) + self.reason.encode()
  378. def check(self) -> None:
  379. """
  380. Check that the close code has a valid value for a close frame.
  381. Raises:
  382. ProtocolError: If the close code is invalid.
  383. """
  384. if not (self.code in EXTERNAL_CLOSE_CODES or 3000 <= self.code < 5000):
  385. raise ProtocolError("invalid status code")
  386. def is_utf8_fragment(
  387. data: bytes,
  388. must_start_clean: bool = False,
  389. must_end_clean: bool = False,
  390. ) -> bool:
  391. """Guess if data is a fragment of UTF-8 text."""
  392. # Possible byte sequences for UTF-8 characters are:
  393. # 0xxxxxxx
  394. # 110xxxxx 10xxxxxx
  395. # 1110xxxx 10xxxxxx 10xxxxxx
  396. # 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  397. # The algorithm determines ``start`` and ``end`` so that ``data[start:end]``
  398. # must be a valid UTF-8 sequence for data to be a valid UTF-8 fragment.
  399. start, end = 0, len(data)
  400. if not must_start_clean:
  401. # Remove continuation bytes from the beginning.
  402. max_start = min(3, len(data))
  403. while start < max_start:
  404. byte = data[start]
  405. # Continuation byte
  406. if byte & 0b11000000 == 0b10000000:
  407. start += 1
  408. continue
  409. break
  410. if not must_end_clean:
  411. # Remove a partial multibyte sequence from the end.
  412. end -= 1 # index of the last byte
  413. min_end = max(len(data) - 4, start)
  414. while end >= min_end:
  415. byte = data[end]
  416. # Continuation byte
  417. if byte & 0b11000000 == 0b10000000:
  418. end -= 1
  419. continue
  420. # ASCII byte
  421. if byte & 0b10000000 == 0b00000000:
  422. seq_len = 1
  423. # Leading byte of a 2-byte sequence
  424. elif byte & 0b11100000 == 0b11000000:
  425. seq_len = 2
  426. # Leading byte of a 3-byte sequence
  427. elif byte & 0b11110000 == 0b11100000:
  428. seq_len = 3
  429. # Leading byte of a 4-byte sequence
  430. elif byte & 0b11111000 == 0b11110000:
  431. seq_len = 4
  432. # Invalid byte
  433. else:
  434. seq_len = 0
  435. # Cut only when there's an incomplete sequence at the end.
  436. if seq_len <= len(data) - end:
  437. end = len(data)
  438. break
  439. try:
  440. text = data[start:end].decode()
  441. except UnicodeDecodeError:
  442. return False
  443. else:
  444. # Non-printable characters signal binary data.
  445. return "\\x" not in repr(text)
  446. # At the bottom to break import cycles created by type annotations.
  447. from . import extensions # noqa: E402