2016-08-28 14:43:00 +03:00
|
|
|
# Python rough implementation of a C# TCP client
|
2017-09-04 18:18:33 +03:00
|
|
|
import errno
|
2016-08-26 13:58:53 +03:00
|
|
|
import socket
|
2017-09-04 18:18:33 +03:00
|
|
|
from datetime import timedelta
|
2017-06-09 12:42:39 +03:00
|
|
|
from io import BytesIO, BufferedWriter
|
2017-09-13 10:44:58 +03:00
|
|
|
from threading import Lock
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
|
|
|
|
class TcpClient:
|
2017-09-02 20:33:42 +03:00
|
|
|
def __init__(self, proxy=None, timeout=timedelta(seconds=5)):
|
2017-05-30 11:40:33 +03:00
|
|
|
self._proxy = proxy
|
2017-08-29 14:35:56 +03:00
|
|
|
self._socket = None
|
2017-09-13 10:44:58 +03:00
|
|
|
self._closing_lock = Lock()
|
|
|
|
|
2017-09-02 20:33:42 +03:00
|
|
|
if isinstance(timeout, timedelta):
|
|
|
|
self._timeout = timeout.seconds
|
|
|
|
elif isinstance(timeout, int) or isinstance(timeout, float):
|
|
|
|
self._timeout = float(timeout)
|
|
|
|
else:
|
|
|
|
raise ValueError('Invalid timeout type', type(timeout))
|
2017-05-09 20:05:14 +03:00
|
|
|
|
2017-08-29 14:49:41 +03:00
|
|
|
def _recreate_socket(self, mode):
|
2017-05-30 12:42:14 +03:00
|
|
|
if self._proxy is None:
|
2017-08-29 14:49:41 +03:00
|
|
|
self._socket = socket.socket(mode, socket.SOCK_STREAM)
|
2017-05-30 12:42:14 +03:00
|
|
|
else:
|
2017-05-30 11:40:33 +03:00
|
|
|
import socks
|
2017-08-29 14:49:41 +03:00
|
|
|
self._socket = socks.socksocket(mode, socket.SOCK_STREAM)
|
2017-06-05 07:04:01 +03:00
|
|
|
if type(self._proxy) is dict:
|
|
|
|
self._socket.set_proxy(**self._proxy)
|
|
|
|
else: # tuple, list, etc.
|
|
|
|
self._socket.set_proxy(*self._proxy)
|
2017-05-30 11:40:33 +03:00
|
|
|
|
2017-09-02 20:33:42 +03:00
|
|
|
def connect(self, ip, port):
|
2017-06-22 20:21:33 +03:00
|
|
|
"""Connects to the specified IP and port number.
|
|
|
|
'timeout' must be given in seconds
|
|
|
|
"""
|
2017-04-29 21:57:08 +03:00
|
|
|
if not self.connected:
|
2017-08-29 14:49:41 +03:00
|
|
|
if ':' in ip: # IPv6
|
2017-09-02 20:14:11 +03:00
|
|
|
mode, address = socket.AF_INET6, (ip, port, 0, 0)
|
2017-08-29 14:49:41 +03:00
|
|
|
else:
|
2017-09-02 20:14:11 +03:00
|
|
|
mode, address = socket.AF_INET, (ip, port)
|
|
|
|
|
|
|
|
self._recreate_socket(mode)
|
2017-09-02 20:33:42 +03:00
|
|
|
self._socket.settimeout(self._timeout)
|
2017-09-02 20:14:11 +03:00
|
|
|
self._socket.connect(address)
|
2017-08-29 14:35:56 +03:00
|
|
|
|
|
|
|
def _get_connected(self):
|
|
|
|
return self._socket is not None
|
|
|
|
|
|
|
|
connected = property(fget=_get_connected)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def close(self):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Closes the connection"""
|
2017-09-13 10:44:58 +03:00
|
|
|
if self._closing_lock.locked():
|
|
|
|
# Already closing, no need to close again (avoid None.close())
|
|
|
|
return
|
|
|
|
|
|
|
|
with self._closing_lock:
|
|
|
|
try:
|
|
|
|
if self._socket is not None:
|
|
|
|
self._socket.shutdown(socket.SHUT_RDWR)
|
|
|
|
self._socket.close()
|
|
|
|
except OSError:
|
|
|
|
pass # Ignore ENOTCONN, EBADF, and any other error when closing
|
|
|
|
finally:
|
|
|
|
self._socket = None
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def write(self, data):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Writes (sends) the specified bytes to the connected peer"""
|
2016-09-10 11:17:15 +03:00
|
|
|
|
2017-09-02 20:14:11 +03:00
|
|
|
# TODO Timeout may be an issue when sending the data, Changed in v3.5:
|
|
|
|
# The socket timeout is now the maximum total duration to send all data.
|
2017-09-02 19:49:29 +03:00
|
|
|
try:
|
2017-09-02 20:14:11 +03:00
|
|
|
self._socket.sendall(data)
|
2017-09-03 11:01:00 +03:00
|
|
|
except socket.timeout as e:
|
|
|
|
raise TimeoutError() from e
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
|
|
|
if e.errno == errno.EBADF:
|
|
|
|
self._raise_connection_reset()
|
|
|
|
else:
|
|
|
|
raise
|
2017-09-02 19:49:29 +03:00
|
|
|
except BrokenPipeError:
|
2017-09-03 12:54:26 +03:00
|
|
|
self._raise_connection_reset()
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2017-09-02 20:33:42 +03:00
|
|
|
def read(self, size):
|
2017-06-09 12:42:39 +03:00
|
|
|
"""Reads (receives) a whole block of 'size bytes
|
|
|
|
from the connected peer.
|
|
|
|
|
|
|
|
A timeout can be specified, which will cancel the operation if
|
|
|
|
no data has been read in the specified time. If data was read
|
|
|
|
and it's waiting for more, the timeout will NOT cancel the
|
|
|
|
operation. Set to None for no timeout
|
|
|
|
"""
|
2017-09-02 20:14:11 +03:00
|
|
|
# TODO Remove the timeout from this method, always use previous one
|
2017-09-02 19:49:29 +03:00
|
|
|
with BufferedWriter(BytesIO(), buffer_size=size) as buffer:
|
|
|
|
bytes_left = size
|
|
|
|
while bytes_left != 0:
|
2017-09-03 11:01:00 +03:00
|
|
|
try:
|
|
|
|
partial = self._socket.recv(bytes_left)
|
|
|
|
except socket.timeout as e:
|
|
|
|
raise TimeoutError() from e
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
|
|
|
if e.errno == errno.EBADF:
|
|
|
|
self._raise_connection_reset()
|
|
|
|
else:
|
|
|
|
raise
|
2017-09-03 11:01:00 +03:00
|
|
|
|
2017-09-02 20:14:11 +03:00
|
|
|
if len(partial) == 0:
|
2017-09-03 12:54:26 +03:00
|
|
|
self._raise_connection_reset()
|
2017-09-02 19:49:29 +03:00
|
|
|
|
2017-09-02 20:14:11 +03:00
|
|
|
buffer.write(partial)
|
|
|
|
bytes_left -= len(partial)
|
2017-09-02 19:49:29 +03:00
|
|
|
|
|
|
|
# If everything went fine, return the read bytes
|
|
|
|
buffer.flush()
|
|
|
|
return buffer.raw.getvalue()
|
2017-09-03 12:54:26 +03:00
|
|
|
|
|
|
|
def _raise_connection_reset(self):
|
|
|
|
self.close() # Connection reset -> flag as socket closed
|
|
|
|
raise ConnectionResetError('The server has closed the connection.')
|