v0.166.0
  1"""RFC 6455 WebSocket frame codec.
  2
  3Frames in, frames out — nothing else. This module knows how a single frame is
  4laid out on the wire, how masking works, what a close payload means, and how
  5the two handshake values (`Sec-WebSocket-Accept`, `Sec-WebSocket-Protocol`) are
  6computed. It does not assemble messages from fragments, validate an upgrade
  7request, speak the close handshake, or negotiate extensions — those live in
  8`plain.http.websocket`.
  9
 10No compression. Plain never advertises permessage-deflate, so RSV1 (like RSV2
 11and RSV3) is always a protocol error here.
 12
 13Stdlib only, and no imports from anywhere else in Plain.
 14"""
 15
 16import base64
 17import hashlib
 18import struct
 19import sys
 20from collections.abc import Awaitable, Callable
 21from typing import NamedTuple
 22
 23# Opcodes (RFC 6455 Section 5.2)
 24OP_CONTINUATION = 0x0
 25OP_TEXT = 0x1
 26OP_BINARY = 0x2
 27OP_CLOSE = 0x8
 28OP_PING = 0x9
 29OP_PONG = 0xA
 30
 31_OPCODES = frozenset({OP_CONTINUATION, OP_TEXT, OP_BINARY, OP_CLOSE, OP_PING, OP_PONG})
 32
 33# Close status codes (RFC 6455 Section 7.4.1)
 34CLOSE_NORMAL = 1000
 35CLOSE_GOING_AWAY = 1001
 36CLOSE_PROTOCOL_ERROR = 1002
 37CLOSE_UNSUPPORTED_DATA = 1003
 38CLOSE_NO_STATUS = 1005
 39CLOSE_ABNORMAL = 1006
 40CLOSE_INVALID_PAYLOAD = 1007
 41CLOSE_POLICY_VIOLATION = 1008
 42CLOSE_MESSAGE_TOO_BIG = 1009
 43CLOSE_MANDATORY_EXTENSION = 1010
 44CLOSE_INTERNAL_ERROR = 1011
 45
 46# Control frames carry at most 125 bytes and are never fragmented
 47# (RFC 6455 Section 5.5).
 48MAX_CONTROL_PAYLOAD = 125
 49
 50# Magic GUID for Sec-WebSocket-Accept (RFC 6455 Section 4.2.2)
 51_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
 52
 53
 54class ProtocolError(Exception):
 55    """The peer sent something RFC 6455 forbids. The socket closes with 1002."""
 56
 57
 58class PayloadTooLarge(Exception):
 59    """A frame or message larger than the caller's cap; the socket closes with 1009.
 60
 61    `read_frame` raises it from the header, before a single payload byte is
 62    read, so a declared 4 GiB frame costs nothing. The message layer raises
 63    it again when reassembled fragments pass the cap.
 64    """
 65
 66    def __init__(self, length: int, max_payload: int) -> None:
 67        super().__init__(f"Payload too large: {length} > {max_payload}")
 68        self.length = length
 69        self.max_payload = max_payload
 70
 71
 72class IncompleteFrame(Exception):
 73    """The peer stopped sending. Not a protocol error — the caller decides.
 74
 75    Raised both when the stream ends cleanly on a frame boundary and when it
 76    ends partway through a frame, because `read_frame` only ever asks for bytes
 77    it needs. A reader that was waiting for the next frame treats this as the
 78    connection ending; anything else is an abnormal close.
 79    """
 80
 81
 82class Frame(NamedTuple):
 83    fin: bool
 84    opcode: int
 85    payload: bytes
 86
 87
 88class CloseReason(NamedTuple):
 89    code: int
 90    reason: str
 91
 92
 93def compute_accept_key(key: str) -> str:
 94    """Compute the `Sec-WebSocket-Accept` value for a request's key."""
 95    digest = hashlib.sha1((key + _WS_GUID).encode()).digest()
 96    return base64.b64encode(digest).decode()
 97
 98
 99def apply_mask(data: bytes, mask: bytes) -> bytes:
100    """XOR `data` with the repeating 4-byte `mask` (RFC 6455 Section 5.3).
101
102    Masking is its own inverse, so this both masks and unmasks. The whole
103    payload is XORed as one big integer: faster than any Python-level loop
104    at every size, at the cost of transient integers a few times the
105    payload's size while it runs.
106    """
107    if len(mask) != 4:
108        raise ValueError("Mask must be 4 bytes")
109    n = len(data)
110    if n == 0:
111        return b""
112    repeated_mask = mask * (n // 4) + mask[: n % 4]
113    data_int = int.from_bytes(data, sys.byteorder)
114    mask_int = int.from_bytes(repeated_mask, sys.byteorder)
115    return (data_int ^ mask_int).to_bytes(n, sys.byteorder)
116
117
118def encode_frame(
119    opcode: int, payload: bytes = b"", fin: bool = True, *, mask: bytes | None = None
120) -> bytes:
121    """Encode one frame.
122
123    Server-to-client frames are never masked (the default). A client —
124    the test client, or a test speaking to the server — passes a 4-byte
125    `mask`, which sets the mask bit and masks the payload.
126    """
127    header = bytearray()
128
129    # First byte: FIN, three zero reserved bits, opcode.
130    header.append((0x80 if fin else 0x00) | (opcode & 0x0F))
131
132    # Second byte: the mask bit and the length, which spills into 2 or 8
133    # extra bytes once it no longer fits in 7 bits.
134    mask_bit = 0x80 if mask is not None else 0x00
135    length = len(payload)
136    if length < 126:
137        header.append(mask_bit | length)
138    elif length < 65536:
139        header.append(mask_bit | 126)
140        header.extend(struct.pack("!H", length))
141    else:
142        header.append(mask_bit | 127)
143        header.extend(struct.pack("!Q", length))
144
145    if mask is None:
146        return bytes(header) + payload
147    return bytes(header) + mask + apply_mask(payload, mask)
148
149
150def encode_close(
151    code: int = CLOSE_NORMAL, reason: str = "", *, mask: bytes | None = None
152) -> bytes:
153    """Encode a complete CLOSE frame carrying `code` and `reason`."""
154    payload = struct.pack("!H", code) + reason.encode("utf-8")
155    return encode_frame(OP_CLOSE, payload, mask=mask)
156
157
158def is_valid_close_code(code: int) -> bool:
159    """Is `code` a close code a peer is allowed to put on the wire?
160
161    1004, 1005, 1006 and 1015 are reserved for local use and never sent
162    (RFC 6455 Section 7.4.1).
163    """
164    if 1000 <= code <= 1003:
165        return True
166    if 1007 <= code <= 1014:  # 1012-1014 are IANA-registered
167        return True
168    if 3000 <= code <= 3999:  # libraries and frameworks
169        return True
170    # 4000-4999 is private use. Everything left over (0-999, 1004-1006,
171    # 1015-2999, 5000 and up) is reserved or out of range.
172    return 4000 <= code <= 4999
173
174
175def parse_close_payload(payload: bytes) -> CloseReason:
176    """Parse a CLOSE frame's payload.
177
178    An empty payload means "no status given" — 1005, which is a local code and
179    must never be echoed back onto the wire. Anything malformed is a protocol
180    error: a lone byte, a reserved or out-of-range code, or a reason that is
181    not valid UTF-8.
182    """
183    if len(payload) == 0:
184        return CloseReason(CLOSE_NO_STATUS, "")
185    if len(payload) == 1:
186        raise ProtocolError("Close payload must be empty or at least 2 bytes")
187    code = int.from_bytes(payload[:2], "big")
188    if not is_valid_close_code(code):
189        raise ProtocolError(f"Invalid close code: {code}")
190    try:
191        reason = payload[2:].decode("utf-8")
192    except UnicodeDecodeError:
193        raise ProtocolError("Invalid UTF-8 in close reason") from None
194    return CloseReason(code, reason)
195
196
197async def _read_exactly(recv: Callable[[int], Awaitable[bytes]], n: int) -> bytes:
198    """Read exactly `n` bytes, looping over however many short reads it takes."""
199    if n == 0:
200        return b""
201    chunk = await recv(n)
202    if len(chunk) == n:
203        return chunk
204    if not chunk:
205        raise IncompleteFrame(f"Stream ended, wanted {n} more bytes")
206    parts = [chunk]
207    remaining = n - len(chunk)
208    while remaining > 0:
209        chunk = await recv(remaining)
210        if not chunk:
211            raise IncompleteFrame(f"Stream ended, wanted {remaining} more bytes")
212        parts.append(chunk)
213        remaining -= len(chunk)
214    return b"".join(parts)
215
216
217async def read_frame(
218    recv: Callable[[int], Awaitable[bytes]],
219    max_payload: int,
220    *,
221    require_mask: bool = True,
222) -> Frame:
223    """Read one frame, payload already unmasked.
224
225    `recv(n)` returns up to `n` bytes, or `b""` at end of stream; short reads
226    are normal and are looped over. The stream ending raises `IncompleteFrame`,
227    a violation raises `ProtocolError`, and a declared length above
228    `max_payload` raises `PayloadTooLarge` from the header alone.
229
230    The server reads client frames, which must be masked (the default). A
231    client reading server frames passes `require_mask=False`; a masked
232    frame is still unmasked correctly either way.
233    """
234    header = await _read_exactly(recv, 2)
235    first_byte, second_byte = header[0], header[1]
236
237    fin = bool(first_byte & 0x80)
238    opcode = first_byte & 0x0F
239    masked = bool(second_byte & 0x80)
240    length = second_byte & 0x7F
241
242    # No extension is ever negotiated, so all three reserved bits must be zero.
243    if first_byte & 0x70:
244        raise ProtocolError("Non-zero RSV bits")
245
246    if opcode not in _OPCODES:
247        raise ProtocolError(f"Unknown opcode: {opcode:#x}")
248
249    # Every client-to-server frame is masked (RFC 6455 Section 5.1).
250    if require_mask and not masked:
251        raise ProtocolError("Client frame is not masked")
252
253    if opcode >= OP_CLOSE:
254        if not fin:
255            raise ProtocolError("Fragmented control frame")
256        if length > MAX_CONTROL_PAYLOAD:
257            raise ProtocolError(f"Control frame payload too long: {length}")
258
259    if length == 126:
260        length = int.from_bytes(await _read_exactly(recv, 2), "big")
261    elif length == 127:
262        length = int.from_bytes(await _read_exactly(recv, 8), "big")
263        # The most significant bit of a 64-bit length must be 0
264        # (RFC 6455 Section 5.2).
265        if length & (1 << 63):
266            raise ProtocolError("64-bit payload length has the high bit set")
267
268    # Checked before the payload is touched: a frame that claims gigabytes
269    # must not cost gigabytes to reject. Control frames are bounded by the
270    # protocol's own 125 bytes above, not by the application's cap.
271    if opcode < OP_CLOSE and length > max_payload:
272        raise PayloadTooLarge(length, max_payload)
273
274    if masked:
275        mask = await _read_exactly(recv, 4)
276        payload = apply_mask(await _read_exactly(recv, length), mask)
277    else:
278        payload = await _read_exactly(recv, length)
279
280    return Frame(fin=fin, opcode=opcode, payload=payload)