Debian Codegraph @

src/websockets/legacy/framing.py

raw
1 from __future__ import annotations
2
3 import struct
4 from collections.abc import Awaitable, Sequence
5 from typing import Any, Callable, NamedTuple
6
7 from .. import extensions, frames
8 from ..exceptions import PayloadTooBig, ProtocolError
9 from ..typing import BytesLike, DataLike
10
11
12 try:
13 from ..speedups import apply_mask
14 except ImportError:
15 from ..utils import apply_mask
16
17
18 class Frame(NamedTuple):
19 fin: bool
20 opcode: frames.Opcode
21 data: BytesLike
22 rsv1: bool = False
23 rsv2: bool = False
24 rsv3: bool = False
25
26 @property
27 def new_frame(self) -> frames.Frame:
28 return frames.Frame(
29 self.opcode,
30 self.data,
31 self.fin,
32 self.rsv1,
33 self.rsv2,
34 self.rsv3,
35 )
36
37 def __str__(self) -> str:
38 return str(self.new_frame)
39
40 def check(self) -> None:
41 return self.new_frame.check()
42
43 @classmethod
44 async def read(
45 cls,
46 reader: Callable[[int], Awaitable[bytes]],
47 *,
48 mask: bool,
49 max_size: int | None = None,
50 extensions: Sequence[extensions.Extension] | None = None,
51 ) -> Frame:
52 """
53 Read a WebSocket frame.
54
55 Args:
56 reader: Coroutine that reads exactly the requested number of
57 bytes, unless the end of file is reached.
58 mask: Whether the frame should be masked i.e. whether the read
59 happens on the server side.
60 max_size: Maximum payload size in bytes.
61 extensions: List of extensions, applied in reverse order.
62
63 Raises:
64 PayloadTooBig: If the frame exceeds ``max_size``.
65 ProtocolError: If the frame contains incorrect values.
66
67 """
68
69 # Read the header.
70 data = await reader(2)
71 head1, head2 = struct.unpack("!BB", data)
72
73 # While not Pythonic, this is marginally faster than calling bool().
74 fin = True if head1 & 0b10000000 else False
75 rsv1 = True if head1 & 0b01000000 else False
76 rsv2 = True if head1 & 0b00100000 else False
77 rsv3 = True if head1 & 0b00010000 else False
78
79 try:
80 opcode = frames.Opcode(head1 & 0b00001111)
81 except ValueError as exc:
82 raise ProtocolError("invalid opcode") from exc
83
84 if (True if head2 & 0b10000000 else False) != mask:
85 raise ProtocolError("incorrect masking")
86
87 length = head2 & 0b01111111
88 if length == 126:
89 data = await reader(2)
90 (length,) = struct.unpack("!H", data)
91 elif length == 127:
92 data = await reader(8)
93 (length,) = struct.unpack("!Q", data)
94 if max_size is not None and length > max_size:
95 raise PayloadTooBig(length, max_size)
96 if mask:
97 mask_bits = await reader(4)
98
99 # Read the data.
100 data = await reader(length)
101 if mask:
102 data = apply_mask(data, mask_bits)
103
104 new_frame = frames.Frame(opcode, data, fin, rsv1, rsv2, rsv3)
105
106 if extensions is None:
107 extensions = []
108 for extension in reversed(extensions):
109 new_frame = extension.decode(new_frame, max_size=max_size)
110
111 new_frame.check()
112
113 return cls(
114 new_frame.fin,
115 new_frame.opcode,
116 new_frame.data,
117 new_frame.rsv1,
118 new_frame.rsv2,
119 new_frame.rsv3,
120 )
121
122 def write(
123 self,
124 write: Callable[[bytes], Any],
125 *,
126 mask: bool,
127 extensions: Sequence[extensions.Extension] | None = None,
128 ) -> None:
129 """
130 Write a WebSocket frame.
131
132 Args:
133 frame: Frame to write.
134 write: Function that writes bytes.
135 mask: Whether the frame should be masked i.e. whether the write
136 happens on the client side.
137 extensions: List of extensions, applied in order.
138
139 Raises:
140 ProtocolError: If the frame contains incorrect values.
141
142 """
143 # The frame is written in a single call to write in order to prevent
144 # TCP fragmentation. See #68 for details. This also makes it safe to
145 # send frames concurrently from multiple coroutines.
146 write(self.new_frame.serialize(mask=mask, extensions=extensions))
147
148
149 def prepare_data(data: DataLike) -> tuple[int, BytesLike]:
150 """
151 Convert a string or byte-like object to an opcode and a bytes-like object.
152
153 This function is designed for data frames.
154
155 If ``data`` is a :class:`str`, return ``Opcode.TEXT`` and a :class:`bytes`
156 object encoding ``data`` in UTF-8.
157
158 If ``data`` is a bytes-like object, return ``Opcode.BINARY`` and a
159 bytes-like object.
160
161 Raises:
162 TypeError: If ``data`` doesn't have a supported type.
163
164 """
165 if isinstance(data, str):
166 return frames.Opcode.TEXT, data.encode()
167 elif isinstance(data, BytesLike):
168 return frames.Opcode.BINARY, data
169 else:
170 raise TypeError("data must be str or bytes-like")
171
172
173 def prepare_ctrl(data: DataLike) -> bytes:
174 """
175 Convert a string or byte-like object to bytes.
176
177 This function is designed for ping and pong frames.
178
179 If ``data`` is a :class:`str`, return a :class:`bytes` object encoding
180 ``data`` in UTF-8.
181
182 If ``data`` is a bytes-like object, return a :class:`bytes` object.
183
184 Raises:
185 TypeError: If ``data`` doesn't have a supported type.
186
187 """
188 if isinstance(data, str):
189 return data.encode()
190 elif isinstance(data, BytesLike):
191 return bytes(data)
192 else:
193 raise TypeError("data must be str or bytes-like")
194
195
196 # Backwards compatibility with previously documented public APIs
197 encode_data = prepare_ctrl
198
199 # Backwards compatibility with previously documented public APIs
200 from ..frames import Close # noqa: E402 F401, I001
201
202
203 def parse_close(data: bytes) -> tuple[int, str]:
204 """
205 Parse the payload from a close frame.
206
207 Returns:
208 Close code and reason.
209
210 Raises:
211 ProtocolError: If data is ill-formed.
212 UnicodeDecodeError: If the reason isn't valid UTF-8.
213
214 """
215 close = Close.parse(data)
216 return close.code, close.reason
217
218
219 def serialize_close(code: int, reason: str) -> bytes:
220 """
221 Serialize the payload for a close frame.
222
223 """
224 return Close(code, reason).serialize()