Skip to content

Commit fc3ad51

Browse files
committed
Reduce the complexity of _parse_header
1 parent 79d15d5 commit fc3ad51

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

wsproto/frame_protocol.py

+25-19
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,28 @@ def _consume_exactly(self, nbytes):
142142
yield
143143
return (yield from self._consume_at_most(nbytes))
144144

145+
def _parse_extended_payload_length(self, opcode, payload_len):
146+
if opcode.iscontrol() and payload_len > 125:
147+
raise ParseFailed("Control frame with payload len > 125")
148+
if payload_len == 126:
149+
data = yield from self._consume_exactly(2)
150+
(payload_len,) = struct.unpack("!H", data)
151+
if payload_len <= 125:
152+
raise ParseFailed(
153+
"Payload length used 2 bytes when 1 would have sufficed")
154+
elif payload_len == 127:
155+
data = yield from self._consume_exactly(8)
156+
(payload_len,) = struct.unpack("!Q", data)
157+
if payload_len < 2 ** 16:
158+
raise ParseFailed(
159+
"Payload length used 8 bytes when 2 would have sufficed")
160+
if payload_len >> 63:
161+
# I'm not sure why this is illegal, but that's what the RFC
162+
# says, so...
163+
raise ParseFailed("8-byte payload length with non-zero MSB")
164+
165+
return payload_len
166+
145167
def _parse_header(self):
146168
# returns a Header object
147169
(fin_rsv_opcode,) = yield from self._consume_exactly(1)
@@ -161,25 +183,9 @@ def _parse_header(self):
161183
(mask_len,) = yield from self._consume_exactly(1)
162184
has_mask = bool(mask_len & 0x80)
163185
payload_len = mask_len & 0x7f
164-
165-
if opcode.iscontrol() and payload_len > 125:
166-
raise ParseFailed("Control frame with payload len > 125")
167-
if payload_len == 126:
168-
data = yield from self._consume_exactly(2)
169-
(payload_len,) = struct.unpack("!H", data)
170-
if payload_len <= 125:
171-
raise ParseFailed(
172-
"Payload length used 2 bytes when 1 would have sufficed")
173-
elif payload_len == 127:
174-
data = yield from self._consume_exactly(8)
175-
(payload_len,) = struct.unpack("!Q", data)
176-
if payload_len < 2 ** 16:
177-
raise ParseFailed(
178-
"Payload length used 8 bytes when 2 would have sufficed")
179-
if payload_len >> 63:
180-
# I'm not sure why this is illegal, but that's what the RFC
181-
# says, so...
182-
raise ParseFailed("8-byte payload length with non-zero MSB")
186+
payload_len = yield from self._parse_extended_payload_length(
187+
opcode, payload_len
188+
)
183189

184190
for extension in self.extensions:
185191
result = extension.frame_inbound_header(

0 commit comments

Comments
 (0)