Skip to content

Commit

Permalink
Made parsing of id field of Socket.IO packet faster and more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Apr 12, 2021
1 parent 8d1aeb2 commit 09cb411
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
14 changes: 10 additions & 4 deletions socketio/packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,16 @@ def decode(self, encoded_packet):
if q != -1:
self.namespace = self.namespace[0:q]
if ep and ep[0].isdigit():
self.id = 0
while ep and ep[0].isdigit():
self.id = self.id * 10 + int(ep[0])
ep = ep[1:]
i = 1
end = len(ep)
while i < end:
if not ep[i].isdigit() or i >= 100:
break
i += 1
self.id = int(ep[:i])
ep = ep[i:]
if len(ep) > 0 and ep[0].isdigit():
raise ValueError('id field is too long')
if ep:
self.data = self.json.loads(ep)
return attachment_count
Expand Down
10 changes: 10 additions & 0 deletions tests/common/test_packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,16 @@ def test_decode_id(self):
assert pkt.id == 123
assert pkt.encode() == '2123["foo"]'

def test_decode_id_long(self):
pkt = packet.Packet(encoded_packet='2' + '1' * 100 + '["foo"]')
assert pkt.id == int('1' * 100)
assert pkt.data == ['foo']

def test_decode_id_too_long(self):
with pytest.raises(ValueError):
packet.Packet(encoded_packet='2' + '1' * 101)
packet.Packet(encoded_packet='2' + '1' * 101 + '["foo"]')

def test_encode_id_no_data(self):
pkt = packet.Packet(packet_type=packet.EVENT, id=123)
assert pkt.id == 123
Expand Down

0 comments on commit 09cb411

Please sign in to comment.