|
| 1 | +# Pyrogram - Telegram MTProto API Client Library for Python |
| 2 | +# Copyright (C) 2017 Dan Tès <https://github.com/delivrance> |
| 3 | +# |
| 4 | +# This file is part of Pyrogram. |
| 5 | +# |
| 6 | +# Pyrogram is free software: you can redistribute it and/or modify |
| 7 | +# it under the terms of the GNU Lesser General Public License as published |
| 8 | +# by the Free Software Foundation, either version 3 of the License, or |
| 9 | +# (at your option) any later version. |
| 10 | +# |
| 11 | +# Pyrogram is distributed in the hope that it will be useful, |
| 12 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | +# GNU Lesser General Public License for more details. |
| 15 | +# |
| 16 | +# You should have received a copy of the GNU Lesser General Public License |
| 17 | +# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. |
| 18 | + |
| 19 | +import logging |
| 20 | +from binascii import crc32 |
| 21 | +from struct import pack, unpack |
| 22 | +from threading import Lock |
| 23 | + |
| 24 | +from .tcp import TCP |
| 25 | + |
| 26 | +log = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +class TCPFull(TCP): |
| 30 | + def __init__(self): |
| 31 | + super().__init__() |
| 32 | + self.seq_no = None |
| 33 | + self.lock = Lock() |
| 34 | + |
| 35 | + def connect(self, address: tuple): |
| 36 | + super().connect(address) |
| 37 | + self.seq_no = 0 |
| 38 | + log.info("Connected!") |
| 39 | + |
| 40 | + def send(self, data: bytes): |
| 41 | + with self.lock: |
| 42 | + # 12 = packet_length (4), seq_no (4), crc32 (4) (at the end) |
| 43 | + data = pack("<II", len(data) + 12, self.seq_no) + data |
| 44 | + data += pack("<I", crc32(data)) |
| 45 | + |
| 46 | + self.seq_no += 1 |
| 47 | + |
| 48 | + super().sendall(data) |
| 49 | + |
| 50 | + def recv(self) -> bytes or None: |
| 51 | + length = self.recvall(4) |
| 52 | + |
| 53 | + if length is None: |
| 54 | + return None |
| 55 | + |
| 56 | + packet = self.recvall(unpack("<I", length)[0] - 4) |
| 57 | + |
| 58 | + if packet is None: |
| 59 | + return None |
| 60 | + |
| 61 | + packet = length + packet # Whole data + checksum |
| 62 | + checksum = packet[-4:] # Checksum is at the last 4 bytes |
| 63 | + packet = packet[:-4] # Data without checksum |
| 64 | + |
| 65 | + if crc32(packet) != unpack("<I", checksum)[0]: |
| 66 | + return None |
| 67 | + |
| 68 | + return packet[8:] # Skip packet_length (4) and tcp_seq_no (4) |
0 commit comments