frames.py 16 KB

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