Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

431 linhas
12 KiB

  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, Union
  10. from .exceptions import PayloadTooBig, ProtocolError
  11. try:
  12. from .speedups import apply_mask
  13. except ImportError:
  14. from .utils import apply_mask
  15. __all__ = [
  16. "Opcode",
  17. "OP_CONT",
  18. "OP_TEXT",
  19. "OP_BINARY",
  20. "OP_CLOSE",
  21. "OP_PING",
  22. "OP_PONG",
  23. "DATA_OPCODES",
  24. "CTRL_OPCODES",
  25. "CloseCode",
  26. "Frame",
  27. "Close",
  28. ]
  29. class Opcode(enum.IntEnum):
  30. """Opcode values for WebSocket frames."""
  31. CONT, TEXT, BINARY = 0x00, 0x01, 0x02
  32. CLOSE, PING, PONG = 0x08, 0x09, 0x0A
  33. OP_CONT = Opcode.CONT
  34. OP_TEXT = Opcode.TEXT
  35. OP_BINARY = Opcode.BINARY
  36. OP_CLOSE = Opcode.CLOSE
  37. OP_PING = Opcode.PING
  38. OP_PONG = Opcode.PONG
  39. DATA_OPCODES = OP_CONT, OP_TEXT, OP_BINARY
  40. CTRL_OPCODES = OP_CLOSE, OP_PING, OP_PONG
  41. class CloseCode(enum.IntEnum):
  42. """Close code values for WebSocket close frames."""
  43. NORMAL_CLOSURE = 1000
  44. GOING_AWAY = 1001
  45. PROTOCOL_ERROR = 1002
  46. UNSUPPORTED_DATA = 1003
  47. # 1004 is reserved
  48. NO_STATUS_RCVD = 1005
  49. ABNORMAL_CLOSURE = 1006
  50. INVALID_DATA = 1007
  51. POLICY_VIOLATION = 1008
  52. MESSAGE_TOO_BIG = 1009
  53. MANDATORY_EXTENSION = 1010
  54. INTERNAL_ERROR = 1011
  55. SERVICE_RESTART = 1012
  56. TRY_AGAIN_LATER = 1013
  57. BAD_GATEWAY = 1014
  58. TLS_HANDSHAKE = 1015
  59. # See https://www.iana.org/assignments/websocket/websocket.xhtml
  60. CLOSE_CODE_EXPLANATIONS: dict[int, str] = {
  61. CloseCode.NORMAL_CLOSURE: "OK",
  62. CloseCode.GOING_AWAY: "going away",
  63. CloseCode.PROTOCOL_ERROR: "protocol error",
  64. CloseCode.UNSUPPORTED_DATA: "unsupported data",
  65. CloseCode.NO_STATUS_RCVD: "no status received [internal]",
  66. CloseCode.ABNORMAL_CLOSURE: "abnormal closure [internal]",
  67. CloseCode.INVALID_DATA: "invalid frame payload data",
  68. CloseCode.POLICY_VIOLATION: "policy violation",
  69. CloseCode.MESSAGE_TOO_BIG: "message too big",
  70. CloseCode.MANDATORY_EXTENSION: "mandatory extension",
  71. CloseCode.INTERNAL_ERROR: "internal error",
  72. CloseCode.SERVICE_RESTART: "service restart",
  73. CloseCode.TRY_AGAIN_LATER: "try again later",
  74. CloseCode.BAD_GATEWAY: "bad gateway",
  75. CloseCode.TLS_HANDSHAKE: "TLS handshake failure [internal]",
  76. }
  77. # Close code that are allowed in a close frame.
  78. # Using a set optimizes `code in EXTERNAL_CLOSE_CODES`.
  79. EXTERNAL_CLOSE_CODES = {
  80. CloseCode.NORMAL_CLOSURE,
  81. CloseCode.GOING_AWAY,
  82. CloseCode.PROTOCOL_ERROR,
  83. CloseCode.UNSUPPORTED_DATA,
  84. CloseCode.INVALID_DATA,
  85. CloseCode.POLICY_VIOLATION,
  86. CloseCode.MESSAGE_TOO_BIG,
  87. CloseCode.MANDATORY_EXTENSION,
  88. CloseCode.INTERNAL_ERROR,
  89. CloseCode.SERVICE_RESTART,
  90. CloseCode.TRY_AGAIN_LATER,
  91. CloseCode.BAD_GATEWAY,
  92. }
  93. OK_CLOSE_CODES = {
  94. CloseCode.NORMAL_CLOSURE,
  95. CloseCode.GOING_AWAY,
  96. CloseCode.NO_STATUS_RCVD,
  97. }
  98. BytesLike = bytes, bytearray, memoryview
  99. @dataclasses.dataclass
  100. class Frame:
  101. """
  102. WebSocket frame.
  103. Attributes:
  104. opcode: Opcode.
  105. data: Payload data.
  106. fin: FIN bit.
  107. rsv1: RSV1 bit.
  108. rsv2: RSV2 bit.
  109. rsv3: RSV3 bit.
  110. Only these fields are needed. The MASK bit, payload length and masking-key
  111. are handled on the fly when parsing and serializing frames.
  112. """
  113. opcode: Opcode
  114. data: Union[bytes, bytearray, memoryview]
  115. fin: bool = True
  116. rsv1: bool = False
  117. rsv2: bool = False
  118. rsv3: bool = False
  119. # Configure if you want to see more in logs. Should be a multiple of 3.
  120. MAX_LOG_SIZE = int(os.environ.get("WEBSOCKETS_MAX_LOG_SIZE", "75"))
  121. def __str__(self) -> str:
  122. """
  123. Return a human-readable representation of a frame.
  124. """
  125. coding = None
  126. length = f"{len(self.data)} byte{'' if len(self.data) == 1 else 's'}"
  127. non_final = "" if self.fin else "continued"
  128. if self.opcode is OP_TEXT:
  129. # Decoding only the beginning and the end is needlessly hard.
  130. # Decode the entire payload then elide later if necessary.
  131. data = repr(bytes(self.data).decode())
  132. elif self.opcode is OP_BINARY:
  133. # We'll show at most the first 16 bytes and the last 8 bytes.
  134. # Encode just what we need, plus two dummy bytes to elide later.
  135. binary = self.data
  136. if len(binary) > self.MAX_LOG_SIZE // 3:
  137. cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8
  138. binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]])
  139. data = " ".join(f"{byte:02x}" for byte in binary)
  140. elif self.opcode is OP_CLOSE:
  141. data = str(Close.parse(self.data))
  142. elif self.data:
  143. # We don't know if a Continuation frame contains text or binary.
  144. # Ping and Pong frames could contain UTF-8.
  145. # Attempt to decode as UTF-8 and display it as text; fallback to
  146. # binary. If self.data is a memoryview, it has no decode() method,
  147. # which raises AttributeError.
  148. try:
  149. data = repr(bytes(self.data).decode())
  150. coding = "text"
  151. except (UnicodeDecodeError, AttributeError):
  152. binary = self.data
  153. if len(binary) > self.MAX_LOG_SIZE // 3:
  154. cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8
  155. binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]])
  156. data = " ".join(f"{byte:02x}" for byte in binary)
  157. coding = "binary"
  158. else:
  159. data = "''"
  160. if len(data) > self.MAX_LOG_SIZE:
  161. cut = self.MAX_LOG_SIZE // 3 - 1 # by default cut = 24
  162. data = data[: 2 * cut] + "..." + data[-cut:]
  163. metadata = ", ".join(filter(None, [coding, length, non_final]))
  164. return f"{self.opcode.name} {data} [{metadata}]"
  165. @classmethod
  166. def parse(
  167. cls,
  168. read_exact: Callable[[int], Generator[None, None, bytes]],
  169. *,
  170. mask: bool,
  171. max_size: int | None = None,
  172. extensions: Sequence[extensions.Extension] | None = None,
  173. ) -> Generator[None, None, Frame]:
  174. """
  175. Parse a WebSocket frame.
  176. This is a generator-based coroutine.
  177. Args:
  178. read_exact: Generator-based coroutine that reads the requested
  179. bytes or raises an exception if there isn't enough data.
  180. mask: Whether the frame should be masked i.e. whether the read
  181. happens on the server side.
  182. max_size: Maximum payload size in bytes.
  183. extensions: List of extensions, applied in reverse order.
  184. Raises:
  185. EOFError: If the connection is closed without a full WebSocket frame.
  186. PayloadTooBig: If the frame's payload size exceeds ``max_size``.
  187. ProtocolError: If the frame contains incorrect values.
  188. """
  189. # Read the header.
  190. data = yield from read_exact(2)
  191. head1, head2 = struct.unpack("!BB", data)
  192. # While not Pythonic, this is marginally faster than calling bool().
  193. fin = True if head1 & 0b10000000 else False
  194. rsv1 = True if head1 & 0b01000000 else False
  195. rsv2 = True if head1 & 0b00100000 else False
  196. rsv3 = True if head1 & 0b00010000 else False
  197. try:
  198. opcode = Opcode(head1 & 0b00001111)
  199. except ValueError as exc:
  200. raise ProtocolError("invalid opcode") from exc
  201. if (True if head2 & 0b10000000 else False) != mask:
  202. raise ProtocolError("incorrect masking")
  203. length = head2 & 0b01111111
  204. if length == 126:
  205. data = yield from read_exact(2)
  206. (length,) = struct.unpack("!H", data)
  207. elif length == 127:
  208. data = yield from read_exact(8)
  209. (length,) = struct.unpack("!Q", data)
  210. if max_size is not None and length > max_size:
  211. raise PayloadTooBig(length, max_size)
  212. if mask:
  213. mask_bytes = yield from read_exact(4)
  214. # Read the data.
  215. data = yield from read_exact(length)
  216. if mask:
  217. data = apply_mask(data, mask_bytes)
  218. frame = cls(opcode, data, fin, rsv1, rsv2, rsv3)
  219. if extensions is None:
  220. extensions = []
  221. for extension in reversed(extensions):
  222. frame = extension.decode(frame, max_size=max_size)
  223. frame.check()
  224. return frame
  225. def serialize(
  226. self,
  227. *,
  228. mask: bool,
  229. extensions: Sequence[extensions.Extension] | None = None,
  230. ) -> bytes:
  231. """
  232. Serialize a WebSocket frame.
  233. Args:
  234. mask: Whether the frame should be masked i.e. whether the write
  235. happens on the client side.
  236. extensions: List of extensions, applied in order.
  237. Raises:
  238. ProtocolError: If the frame contains incorrect values.
  239. """
  240. self.check()
  241. if extensions is None:
  242. extensions = []
  243. for extension in extensions:
  244. self = extension.encode(self)
  245. output = io.BytesIO()
  246. # Prepare the header.
  247. head1 = (
  248. (0b10000000 if self.fin else 0)
  249. | (0b01000000 if self.rsv1 else 0)
  250. | (0b00100000 if self.rsv2 else 0)
  251. | (0b00010000 if self.rsv3 else 0)
  252. | self.opcode
  253. )
  254. head2 = 0b10000000 if mask else 0
  255. length = len(self.data)
  256. if length < 126:
  257. output.write(struct.pack("!BB", head1, head2 | length))
  258. elif length < 65536:
  259. output.write(struct.pack("!BBH", head1, head2 | 126, length))
  260. else:
  261. output.write(struct.pack("!BBQ", head1, head2 | 127, length))
  262. if mask:
  263. mask_bytes = secrets.token_bytes(4)
  264. output.write(mask_bytes)
  265. # Prepare the data.
  266. if mask:
  267. data = apply_mask(self.data, mask_bytes)
  268. else:
  269. data = self.data
  270. output.write(data)
  271. return output.getvalue()
  272. def check(self) -> None:
  273. """
  274. Check that reserved bits and opcode have acceptable values.
  275. Raises:
  276. ProtocolError: If a reserved bit or the opcode is invalid.
  277. """
  278. if self.rsv1 or self.rsv2 or self.rsv3:
  279. raise ProtocolError("reserved bits must be 0")
  280. if self.opcode in CTRL_OPCODES:
  281. if len(self.data) > 125:
  282. raise ProtocolError("control frame too long")
  283. if not self.fin:
  284. raise ProtocolError("fragmented control frame")
  285. @dataclasses.dataclass
  286. class Close:
  287. """
  288. Code and reason for WebSocket close frames.
  289. Attributes:
  290. code: Close code.
  291. reason: Close reason.
  292. """
  293. code: int
  294. reason: str
  295. def __str__(self) -> str:
  296. """
  297. Return a human-readable representation of a close code and reason.
  298. """
  299. if 3000 <= self.code < 4000:
  300. explanation = "registered"
  301. elif 4000 <= self.code < 5000:
  302. explanation = "private use"
  303. else:
  304. explanation = CLOSE_CODE_EXPLANATIONS.get(self.code, "unknown")
  305. result = f"{self.code} ({explanation})"
  306. if self.reason:
  307. result = f"{result} {self.reason}"
  308. return result
  309. @classmethod
  310. def parse(cls, data: bytes) -> Close:
  311. """
  312. Parse the payload of a close frame.
  313. Args:
  314. data: Payload of the close frame.
  315. Raises:
  316. ProtocolError: If data is ill-formed.
  317. UnicodeDecodeError: If the reason isn't valid UTF-8.
  318. """
  319. if len(data) >= 2:
  320. (code,) = struct.unpack("!H", data[:2])
  321. reason = data[2:].decode()
  322. close = cls(code, reason)
  323. close.check()
  324. return close
  325. elif len(data) == 0:
  326. return cls(CloseCode.NO_STATUS_RCVD, "")
  327. else:
  328. raise ProtocolError("close frame too short")
  329. def serialize(self) -> bytes:
  330. """
  331. Serialize the payload of a close frame.
  332. """
  333. self.check()
  334. return struct.pack("!H", self.code) + self.reason.encode()
  335. def check(self) -> None:
  336. """
  337. Check that the close code has a valid value for a close frame.
  338. Raises:
  339. ProtocolError: If the close code is invalid.
  340. """
  341. if not (self.code in EXTERNAL_CLOSE_CODES or 3000 <= self.code < 5000):
  342. raise ProtocolError("invalid status code")
  343. # At the bottom to break import cycles created by type annotations.
  344. from . import extensions # noqa: E402