2016-08-28 14:43:00 +03:00
|
|
|
# This file is based on TLSharp
|
|
|
|
# https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/Network/TcpTransport.cs
|
2016-09-04 13:42:11 +03:00
|
|
|
from network import TcpMessage, TcpClient
|
2016-09-04 22:07:09 +03:00
|
|
|
from binascii import crc32
|
2016-09-05 19:35:12 +03:00
|
|
|
from errors import *
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
|
|
|
|
class TcpTransport:
|
|
|
|
def __init__(self, ip_address, port):
|
|
|
|
self._tcp_client = TcpClient()
|
|
|
|
self._send_counter = 0
|
|
|
|
|
|
|
|
self._tcp_client.connect(ip_address, port)
|
|
|
|
|
|
|
|
def send(self, packet):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Sends the given packet (bytes array) to the connected peer"""
|
2016-08-26 13:58:53 +03:00
|
|
|
if not self._tcp_client.connected:
|
|
|
|
raise ConnectionError('Client not connected to server.')
|
|
|
|
|
2016-08-28 14:43:00 +03:00
|
|
|
# Get a TcpMessage which contains the given packet
|
2016-08-26 13:58:53 +03:00
|
|
|
tcp_message = TcpMessage(self._send_counter, packet)
|
|
|
|
|
|
|
|
self._tcp_client.write(tcp_message.encode())
|
|
|
|
self._send_counter += 1
|
|
|
|
|
|
|
|
def receive(self):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Receives a TcpMessage from the connected peer"""
|
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
# First read everything
|
|
|
|
packet_length_bytes = self._tcp_client.read(4)
|
2016-09-03 11:54:58 +03:00
|
|
|
packet_length = int.from_bytes(packet_length_bytes, byteorder='little')
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
seq_bytes = self._tcp_client.read(4)
|
2016-09-03 11:54:58 +03:00
|
|
|
seq = int.from_bytes(seq_bytes, byteorder='little')
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
body = self._tcp_client.read(packet_length - 12)
|
|
|
|
|
2016-09-04 22:07:09 +03:00
|
|
|
checksum = int.from_bytes(self._tcp_client.read(4), byteorder='little', signed=False)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
# Then perform the checks
|
|
|
|
rv = packet_length_bytes + seq_bytes + body
|
2016-09-04 22:07:09 +03:00
|
|
|
valid_checksum = crc32(rv)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
if checksum != valid_checksum:
|
2016-09-05 19:35:12 +03:00
|
|
|
raise InvalidChecksumError(checksum, valid_checksum)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2016-08-28 14:43:00 +03:00
|
|
|
# If we passed the tests, we can then return a valid TcpMessage
|
2016-08-26 13:58:53 +03:00
|
|
|
return TcpMessage(seq, body)
|
|
|
|
|
2016-09-06 19:54:49 +03:00
|
|
|
def close(self):
|
2016-08-26 13:58:53 +03:00
|
|
|
if self._tcp_client.connected:
|
|
|
|
self._tcp_client.close()
|