2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
This module contains the BinaryReader utility class.
|
|
|
|
"""
|
2016-11-30 00:29:42 +03:00
|
|
|
import os
|
2019-08-07 11:33:46 +03:00
|
|
|
import time
|
2019-08-01 19:47:38 +03:00
|
|
|
from datetime import datetime, timezone, timedelta
|
2019-08-07 11:33:46 +03:00
|
|
|
from io import BytesIO
|
2016-08-30 14:11:19 +03:00
|
|
|
from struct import unpack
|
2016-11-30 00:29:42 +03:00
|
|
|
|
2017-12-28 02:22:28 +03:00
|
|
|
from ..errors import TypeNotFoundError
|
2021-09-12 13:16:02 +03:00
|
|
|
from .. import _tl
|
2021-09-12 17:58:06 +03:00
|
|
|
from ..types import _core
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2019-08-01 19:47:38 +03:00
|
|
|
_EPOCH_NAIVE = datetime(*time.gmtime(0)[:6])
|
|
|
|
_EPOCH = _EPOCH_NAIVE.replace(tzinfo=timezone.utc)
|
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
class BinaryReader:
|
|
|
|
"""
|
|
|
|
Small utility class to read binary data.
|
|
|
|
"""
|
2016-11-30 00:29:42 +03:00
|
|
|
|
2019-08-07 11:33:46 +03:00
|
|
|
def __init__(self, data):
|
|
|
|
self.stream = BytesIO(data)
|
2017-09-18 12:45:08 +03:00
|
|
|
self._last = None # Should come in handy to spot -404 errors
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
# region Reading
|
|
|
|
|
2017-09-04 18:10:04 +03:00
|
|
|
# "All numbers are written as little endian."
|
|
|
|
# https://core.telegram.org/mtproto
|
2016-08-30 14:11:19 +03:00
|
|
|
def read_byte(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a single byte value."""
|
2016-09-03 11:54:58 +03:00
|
|
|
return self.read(1)[0]
|
2016-08-30 14:11:19 +03:00
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
def read_int(self, signed=True):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads an integer (4 bytes) value."""
|
2016-09-03 11:54:58 +03:00
|
|
|
return int.from_bytes(self.read(4), byteorder='little', signed=signed)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def read_long(self, signed=True):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a long integer (8 bytes) value."""
|
2016-09-03 11:54:58 +03:00
|
|
|
return int.from_bytes(self.read(8), byteorder='little', signed=signed)
|
2016-08-30 14:11:19 +03:00
|
|
|
|
|
|
|
def read_float(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a real floating point (4 bytes) value."""
|
2016-09-03 11:54:58 +03:00
|
|
|
return unpack('<f', self.read(4))[0]
|
2016-08-30 14:11:19 +03:00
|
|
|
|
|
|
|
def read_double(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a real floating point (8 bytes) value."""
|
2016-09-03 11:54:58 +03:00
|
|
|
return unpack('<d', self.read(8))[0]
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2016-08-30 14:11:19 +03:00
|
|
|
def read_large_int(self, bits, signed=True):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a n-bits long integer value."""
|
2016-11-30 00:29:42 +03:00
|
|
|
return int.from_bytes(
|
|
|
|
self.read(bits // 8), byteorder='little', signed=signed)
|
2016-08-27 22:49:38 +03:00
|
|
|
|
2019-08-07 11:33:46 +03:00
|
|
|
def read(self, length=-1):
|
|
|
|
"""Read the given amount of bytes, or -1 to read all remaining."""
|
|
|
|
result = self.stream.read(length)
|
|
|
|
if (length >= 0) and (len(result) != length):
|
2017-09-18 12:45:08 +03:00
|
|
|
raise BufferError(
|
|
|
|
'No more data left to read (need {}, got {}: {}); last read {}'
|
|
|
|
.format(length, len(result), repr(result), repr(self._last))
|
|
|
|
)
|
2016-11-30 00:29:42 +03:00
|
|
|
|
2017-09-18 12:45:08 +03:00
|
|
|
self._last = result
|
2016-09-03 11:54:58 +03:00
|
|
|
return result
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def get_bytes(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Gets the byte array representing the current buffer as a whole."""
|
2016-08-30 14:11:19 +03:00
|
|
|
return self.stream.getvalue()
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Telegram custom reading
|
|
|
|
|
|
|
|
def tgread_bytes(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
Reads a Telegram-encoded byte array, without the need of
|
|
|
|
specifying its length.
|
2017-09-04 18:10:04 +03:00
|
|
|
"""
|
2016-08-30 14:11:19 +03:00
|
|
|
first_byte = self.read_byte()
|
2016-08-26 13:58:53 +03:00
|
|
|
if first_byte == 254:
|
2016-11-30 00:29:42 +03:00
|
|
|
length = self.read_byte() | (self.read_byte() << 8) | (
|
|
|
|
self.read_byte() << 16)
|
2016-08-26 13:58:53 +03:00
|
|
|
padding = length % 4
|
|
|
|
else:
|
|
|
|
length = first_byte
|
|
|
|
padding = (length + 1) % 4
|
|
|
|
|
|
|
|
data = self.read(length)
|
|
|
|
if padding > 0:
|
|
|
|
padding = 4 - padding
|
|
|
|
self.read(padding)
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
def tgread_string(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a Telegram-encoded string."""
|
2017-05-03 14:02:44 +03:00
|
|
|
return str(self.tgread_bytes(), encoding='utf-8', errors='replace')
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2016-09-04 22:07:09 +03:00
|
|
|
def tgread_bool(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a Telegram boolean value."""
|
2016-09-04 22:07:09 +03:00
|
|
|
value = self.read_int(signed=False)
|
|
|
|
if value == 0x997275b5: # boolTrue
|
|
|
|
return True
|
|
|
|
elif value == 0xbc799737: # boolFalse
|
|
|
|
return False
|
|
|
|
else:
|
2017-12-28 02:22:28 +03:00
|
|
|
raise RuntimeError('Invalid boolean code {}'.format(hex(value)))
|
2016-09-04 22:07:09 +03:00
|
|
|
|
2016-09-11 11:35:02 +03:00
|
|
|
def tgread_date(self):
|
2017-09-04 18:10:04 +03:00
|
|
|
"""Reads and converts Unix time (used by Telegram)
|
2017-11-26 19:14:28 +03:00
|
|
|
into a Python datetime object.
|
2017-09-04 18:10:04 +03:00
|
|
|
"""
|
2016-09-11 11:35:02 +03:00
|
|
|
value = self.read_int()
|
2019-08-01 19:47:38 +03:00
|
|
|
return _EPOCH + timedelta(seconds=value)
|
2016-09-11 11:35:02 +03:00
|
|
|
|
2016-08-27 22:49:38 +03:00
|
|
|
def tgread_object(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a Telegram object."""
|
2016-09-05 19:35:12 +03:00
|
|
|
constructor_id = self.read_int(signed=False)
|
2021-09-12 17:58:06 +03:00
|
|
|
clazz = _tl.tlobjects.get(constructor_id, None)
|
2016-08-27 22:49:38 +03:00
|
|
|
if clazz is None:
|
2016-09-11 14:10:27 +03:00
|
|
|
# The class was None, but there's still a
|
|
|
|
# chance of it being a manually parsed value like bool!
|
|
|
|
value = constructor_id
|
|
|
|
if value == 0x997275b5: # boolTrue
|
|
|
|
return True
|
|
|
|
elif value == 0xbc799737: # boolFalse
|
|
|
|
return False
|
2018-01-19 14:12:52 +03:00
|
|
|
elif value == 0x1cb5c415: # Vector
|
|
|
|
return [self.tgread_object() for _ in range(self.read_int())]
|
2016-09-11 14:10:27 +03:00
|
|
|
|
2021-09-12 17:58:06 +03:00
|
|
|
clazz = _core.core_objects.get(constructor_id, None)
|
2018-06-09 14:11:49 +03:00
|
|
|
if clazz is None:
|
|
|
|
# If there was still no luck, give up
|
|
|
|
self.seek(-4) # Go back
|
2018-06-09 14:48:27 +03:00
|
|
|
pos = self.tell_position()
|
|
|
|
error = TypeNotFoundError(constructor_id, self.read())
|
|
|
|
self.set_position(pos)
|
|
|
|
raise error
|
2016-08-27 22:49:38 +03:00
|
|
|
|
2017-10-07 14:26:09 +03:00
|
|
|
return clazz.from_reader(self)
|
2016-08-27 22:49:38 +03:00
|
|
|
|
2016-09-26 17:10:07 +03:00
|
|
|
def tgread_vector(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Reads a vector (a list) of Telegram objects."""
|
2016-09-26 17:10:07 +03:00
|
|
|
if 0x1cb5c415 != self.read_int(signed=False):
|
2017-12-28 02:22:28 +03:00
|
|
|
raise RuntimeError('Invalid constructor code, vector was expected')
|
2016-09-26 17:10:07 +03:00
|
|
|
|
|
|
|
count = self.read_int()
|
|
|
|
return [self.tgread_object() for _ in range(count)]
|
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
# endregion
|
|
|
|
|
|
|
|
def close(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Closes the reader, freeing the BytesIO stream."""
|
2019-08-07 11:33:46 +03:00
|
|
|
self.stream.close()
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
# region Position related
|
|
|
|
|
|
|
|
def tell_position(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Tells the current position on the stream."""
|
2019-08-07 11:33:46 +03:00
|
|
|
return self.stream.tell()
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def set_position(self, position):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Sets the current position on the stream."""
|
2019-08-07 11:33:46 +03:00
|
|
|
self.stream.seek(position)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def seek(self, offset):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
Seeks the stream position given an offset from the current position.
|
|
|
|
The offset may be negative.
|
2017-09-04 18:10:04 +03:00
|
|
|
"""
|
2019-08-07 11:33:46 +03:00
|
|
|
self.stream.seek(offset, os.SEEK_CUR)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region with block
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
# endregion
|