2015-02-24 10:54:00 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
Created on Tue Sep 2 19:26:15 2014
|
|
|
|
|
|
|
|
@author: agrigoryev
|
|
|
|
"""
|
2015-02-26 12:03:41 +01:00
|
|
|
from binascii import crc32
|
2015-02-25 16:30:03 +01:00
|
|
|
from datetime import datetime
|
2015-02-26 12:03:41 +01:00
|
|
|
import io
|
2015-03-11 17:55:55 +01:00
|
|
|
import json
|
|
|
|
import socket
|
|
|
|
import struct
|
2015-02-24 10:54:00 +01:00
|
|
|
|
2015-02-25 16:30:03 +01:00
|
|
|
|
|
|
|
def vis(bs):
|
2015-03-11 17:55:55 +01:00
|
|
|
"""
|
|
|
|
Function to visualize byte streams. Split into bytes, print to console.
|
|
|
|
:param bs: BYTE STRING
|
|
|
|
"""
|
|
|
|
symbols_in_one_line = 8
|
|
|
|
n = len(bs) // symbols_in_one_line
|
2015-02-25 16:30:03 +01:00
|
|
|
for i in range(n):
|
2015-03-11 17:55:55 +01:00
|
|
|
print(" ".join(["%02X" % b for b in bs[i*symbols_in_one_line:(i+1)*symbols_in_one_line]])) # for every 8 symbols line
|
|
|
|
print(" ".join(["%02X" % b for b in bs[(i+1)*symbols_in_one_line:]])+"\n") # for last line
|
2015-02-25 16:30:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
class TL:
|
|
|
|
def __init__(self):
|
2015-03-11 17:55:55 +01:00
|
|
|
with open("TL_schema.JSON", 'r') as f:
|
|
|
|
TL_dict = json.load(f)
|
|
|
|
|
|
|
|
self.methods = TL_dict['methods']
|
|
|
|
self.constructors = TL_dict['constructors']
|
|
|
|
|
2015-02-25 16:30:03 +01:00
|
|
|
self.func_dict_id = {}
|
|
|
|
self.func_dict_name = {}
|
|
|
|
self.obj_dict_id = {}
|
|
|
|
self.obj_dict_name = {}
|
|
|
|
|
|
|
|
# Read constructors
|
|
|
|
|
2015-03-11 17:55:55 +01:00
|
|
|
for elem in self.constructors:
|
|
|
|
z = TlElement(elem)
|
|
|
|
self.func_dict_id = {}
|
2015-02-25 16:30:03 +01:00
|
|
|
|
2015-03-11 17:55:55 +01:00
|
|
|
def serialize(self, type_, data):
|
|
|
|
# 1. Type constructor ID
|
|
|
|
# 2. type costructor params
|
2015-02-25 16:30:03 +01:00
|
|
|
|
2015-03-11 17:55:55 +01:00
|
|
|
# Bare types
|
|
|
|
if type_ == 'string':
|
|
|
|
assert isinstance(data, str)
|
|
|
|
struct.pack("<L", len(data))
|
|
|
|
if type_ == 'int':
|
|
|
|
assert isinstance(data, str)
|
|
|
|
struct.pack("<L", len(data))
|
|
|
|
|
|
|
|
def deserialize(self, byte_string, type_=None, subtype=None):
|
|
|
|
|
|
|
|
if isinstance(byte_string, io.BytesIO):
|
|
|
|
bytes_io = byte_string
|
|
|
|
elif isinstance(byte_string, bytes):
|
|
|
|
bytes_io = io.BytesIO(byte_string)
|
2015-02-26 12:46:38 +01:00
|
|
|
else:
|
2015-03-11 17:55:55 +01:00
|
|
|
raise TypeError("Bad input type, use bytes string or BytesIO object")
|
2015-02-26 12:46:38 +01:00
|
|
|
|
|
|
|
# Built-in bare types
|
2015-02-26 12:03:41 +01:00
|
|
|
|
2015-03-11 17:55:55 +01:00
|
|
|
if type_ == 'int':
|
2015-02-26 12:03:41 +01:00
|
|
|
x = struct.unpack('<i', bytes_io.read(4))[0]
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == '#':
|
2015-02-26 12:03:41 +01:00
|
|
|
x = struct.unpack('<I', bytes_io.read(4))[0]
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'long':
|
2015-02-26 12:03:41 +01:00
|
|
|
x = struct.unpack('<q', bytes_io.read(8))[0]
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'double':
|
2015-02-26 12:03:41 +01:00
|
|
|
x = struct.unpack('<d', bytes_io.read(8))[0]
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'int128':
|
2015-02-26 12:03:41 +01:00
|
|
|
t = struct.unpack('<16s', bytes_io.read(16))[0]
|
|
|
|
x = int.from_bytes(t, 'little')
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'int256':
|
2015-02-26 12:03:41 +01:00
|
|
|
t = struct.unpack('<32s', bytes_io.read(32))[0]
|
|
|
|
x = int.from_bytes(t, 'little')
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'bytes':
|
2015-02-26 12:03:41 +01:00
|
|
|
l = int.from_bytes(bytes_io.read(1), 'little')
|
|
|
|
x = bytes_io.read(l)
|
|
|
|
bytes_io.read(-(l+1) % 4) # skip padding bytes
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'string':
|
2015-02-26 12:03:41 +01:00
|
|
|
l = int.from_bytes(bytes_io.read(1), 'little')
|
|
|
|
assert l <=254
|
|
|
|
if l == 254:
|
|
|
|
# We have a long string
|
|
|
|
long_len = int.from_bytes(bytes_io.read(3), 'little')
|
|
|
|
x = bytes_io.read(long_len)
|
|
|
|
bytes_io.read(-long_len % 4) # skip padding bytes
|
|
|
|
else:
|
|
|
|
# We have a short string
|
|
|
|
x = bytes_io.read(l)
|
|
|
|
bytes_io.read(-(l+1) % 4) # skip padding bytes
|
|
|
|
assert isinstance(x, bytes)
|
2015-03-11 17:55:55 +01:00
|
|
|
elif type_ == 'vector':
|
2015-02-26 12:03:41 +01:00
|
|
|
assert subtype is not None
|
|
|
|
count = int.from_bytes(bytes_io.read(4), 'little')
|
2015-03-11 17:55:55 +01:00
|
|
|
x = [self.deserialize(bytes_io, type_=subtype) for i in range(count)]
|
2015-02-26 12:03:41 +01:00
|
|
|
else:
|
2015-02-26 12:46:38 +01:00
|
|
|
# Boxed types
|
|
|
|
|
|
|
|
i = struct.unpack('<i', bytes_io.read(4))[0] # read type ID
|
2015-02-26 12:03:41 +01:00
|
|
|
try:
|
|
|
|
tl_elem = self.obj_dict_id[i]
|
|
|
|
except:
|
2015-03-11 17:55:55 +01:00
|
|
|
raise Exception("Could not extract type: %s" % type_)
|
2015-02-26 12:03:41 +01:00
|
|
|
base_boxed_types = ["Vector", "Int", "Long", "Double", "String", "Int128", "Int256"]
|
|
|
|
if tl_elem.result in base_boxed_types:
|
2015-03-11 17:55:55 +01:00
|
|
|
x = self.deserialize(bytes_io, type_=tl_elem.name, subtype=subtype)
|
2015-02-26 12:03:41 +01:00
|
|
|
|
|
|
|
else: # other types
|
|
|
|
x = {}
|
|
|
|
for arg in tl_elem.args:
|
2015-03-11 17:55:55 +01:00
|
|
|
x[arg['name']] = self.deserialize(bytes_io, type_=arg['type'], subtype=arg['subtype'])
|
2015-02-26 12:03:41 +01:00
|
|
|
return x
|
|
|
|
|
|
|
|
|
2015-02-25 16:30:03 +01:00
|
|
|
class Session:
|
2015-03-11 17:55:55 +01:00
|
|
|
def __init__(self, ip, port):
|
|
|
|
# creating socket
|
2015-02-25 16:30:03 +01:00
|
|
|
self.sock = socket.socket()
|
2015-03-11 17:55:55 +01:00
|
|
|
self.sock.connect((ip, port))
|
|
|
|
self.auth_key_id = None
|
2015-02-25 16:30:03 +01:00
|
|
|
self.number = 0
|
|
|
|
|
2015-03-11 17:55:55 +01:00
|
|
|
def __del__(self):
|
|
|
|
# closing socket when session object is deleted
|
|
|
|
self.sock.close()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def header_unencrypted(message):
|
|
|
|
"""
|
|
|
|
Creating header for the unencrypted message:
|
|
|
|
:param message: byte string to send
|
|
|
|
"""
|
|
|
|
# Basic instructions: https://core.telegram.org/mtproto/description#unencrypted-message
|
|
|
|
|
|
|
|
# Message id: https://core.telegram.org/mtproto/description#message-identifier-msg-id
|
|
|
|
msg_id = int(datetime.utcnow().timestamp()*2**30)*4
|
|
|
|
|
|
|
|
return (b'\x00\x00\x00\x00\x00\x00\x00\x00' +
|
|
|
|
struct.pack('<Q', msg_id) +
|
2015-02-25 16:30:03 +01:00
|
|
|
struct.pack('<L', len(message)))
|
|
|
|
|
2015-03-11 17:55:55 +01:00
|
|
|
# TCP Transport
|
|
|
|
|
|
|
|
# Instructions may be found here: https://core.telegram.org/mtproto#tcp-transport
|
|
|
|
# If a payload (packet) needs to be transmitted from server to client or from client to server,
|
|
|
|
# it is encapsulated as follows: 4 length bytes are added at the front (to include the length,
|
|
|
|
# the sequence number, and CRC32; always divisible by 4) and 4 bytes with the packet sequence number
|
|
|
|
# within this TCP connection (the first packet sent is numbered 0, the next one 1, etc.),
|
|
|
|
# and 4 CRC32 bytes at the end (length, sequence number, and payload together).
|
|
|
|
|
2015-02-25 16:30:03 +01:00
|
|
|
def send_message(self, message):
|
2015-03-11 17:55:55 +01:00
|
|
|
"""
|
|
|
|
Forming the message frame and sending message to server
|
|
|
|
:param message: byte string to send
|
|
|
|
"""
|
|
|
|
|
2015-02-26 12:03:41 +01:00
|
|
|
print('>>')
|
2015-03-11 17:55:55 +01:00
|
|
|
vis(message) # Sending message visualisation to console
|
|
|
|
data = self.header_unencrypted(message) + message
|
2015-02-25 16:30:03 +01:00
|
|
|
step1 = struct.pack('<LL', len(data)+12, self.number) + data
|
2015-02-26 12:03:41 +01:00
|
|
|
step2 = step1 + struct.pack('<L', crc32(step1))
|
2015-02-25 16:30:03 +01:00
|
|
|
self.sock.send(step2)
|
2015-03-11 17:55:55 +01:00
|
|
|
self.number += 1
|
2015-02-25 16:30:03 +01:00
|
|
|
|
|
|
|
def recv_message(self):
|
2015-03-11 17:55:55 +01:00
|
|
|
"""
|
|
|
|
Reading socket and receiving message from server. Check the CRC32 and
|
|
|
|
"""
|
2015-02-25 16:30:03 +01:00
|
|
|
packet_length_data = self.sock.recv(4)
|
|
|
|
if len(packet_length_data) > 0: # if we have smth. in the socket
|
|
|
|
packet_length = struct.unpack("<L", packet_length_data)[0]
|
|
|
|
packet = self.sock.recv(packet_length - 4)
|
|
|
|
self.number = struct.unpack("<L", packet[0:4])[0]
|
2015-02-26 12:03:41 +01:00
|
|
|
auth_key_id = struct.unpack("<8s", packet[4:12])[0]
|
2015-03-11 17:55:55 +01:00
|
|
|
message_id = struct.unpack("<8s", packet[12:20])[0]
|
2015-02-26 12:03:41 +01:00
|
|
|
message_length = struct.unpack("<I", packet[20:24])[0]
|
|
|
|
data = packet[24:24+message_length]
|
2015-02-25 16:30:03 +01:00
|
|
|
crc = packet[-4:]
|
2015-03-11 17:55:55 +01:00
|
|
|
|
|
|
|
# Checking the CRC32 correctness of received data
|
|
|
|
if crc32(packet_length_data + packet[0:-4]).to_bytes(4, 'little') == crc:
|
2015-02-26 12:03:41 +01:00
|
|
|
print('<<')
|
2015-03-11 17:55:55 +01:00
|
|
|
vis(data) # Received message visualisation to console
|
2015-02-25 16:30:03 +01:00
|
|
|
return data
|