Skip to content

Commit

Permalink
Handle unexpected data #206
Browse files Browse the repository at this point in the history
* Reset the buffer if we can't find valid message.
* Ensure that the prefix at the start of the message.
  • Loading branch information
xZetsubou committed Apr 29, 2024
1 parent b705def commit bb90383
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions custom_components/localtuya/core/pytuya/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -612,19 +612,27 @@ def add_data(self, data):
self.buffer += data

header_len = struct.calcsize(MESSAGE_RECV_HEADER_FMT)

while self.buffer:
# Check if enough data for measage header
if len(self.buffer) < header_len:
break

prefix_offset_55AA = self.buffer.find(PREFIX_55AA_BIN)
prefix_offset_6699 = self.buffer.find(PREFIX_6699_BIN)
prefix_offset = (
prefix_offset_6699 if prefix_offset_55AA < 0 else prefix_offset_55AA
)
prefixes = (prefix_offset_55AA, prefix_offset_6699)

self.buffer = self.buffer[prefix_offset:]
# Check if enough data for measage header
if len(self.buffer) < header_len:
# If somehow we got unexpected message, we will ignore it and reset the buffer.
if prefix_offset_55AA < 0 and prefix_offset_6699 < 0:
self.debug(f"Got unexpected Message prefix: {self.buffer}", force=True)
self.buffer = b""
break

# If the prefix is not at the start of the message.
if prefix_offset_55AA != 0 and prefix_offset_6699 != 0:
self.debug(f"Message prefix offset not at the start {self.buffer}")
prefix_offset = min(prefix for prefix in prefixes if not prefix < 0)
self.buffer = self.buffer[prefix_offset:]

header = parse_header(self.buffer, logger=self)
hmac_key = self.local_key if self.version >= 3.4 else None
no_retcode = False
Expand Down

0 comments on commit bb90383

Please sign in to comment.