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-09-22 17:11:07 +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):
|
2017-09-21 14:43:33 +03:00
|
|
|
self.timeout = timeout.seconds
|
2017-10-13 12:38:12 +03:00
|
|
|
elif isinstance(timeout, (int, float)):
|
2017-09-21 14:43:33 +03:00
|
|
|
self.timeout = float(timeout)
|
2017-09-02 20:33:42 +03:00
|
|
|
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-09-22 17:11:07 +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-09-22 17:11:07 +03:00
|
|
|
if type(self.proxy) is dict:
|
|
|
|
self._socket.set_proxy(**self.proxy)
|
2017-06-05 07:04:01 +03:00
|
|
|
else: # tuple, list, etc.
|
2017-09-22 17:11:07 +03:00
|
|
|
self._socket.set_proxy(*self.proxy)
|
2017-05-30 11:40:33 +03:00
|
|
|
|
2017-09-21 14:43:33 +03:00
|
|
|
self._socket.settimeout(self.timeout)
|
2017-09-21 13:37:05 +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-09-21 13:37:05 +03:00
|
|
|
if ':' in ip: # IPv6
|
|
|
|
mode, address = socket.AF_INET6, (ip, port, 0, 0)
|
|
|
|
else:
|
|
|
|
mode, address = socket.AF_INET, (ip, port)
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
2017-09-22 14:14:56 +03:00
|
|
|
while not self._socket:
|
2017-09-21 13:37:05 +03:00
|
|
|
self._recreate_socket(mode)
|
2017-09-02 20:14:11 +03:00
|
|
|
|
2017-09-21 13:37:05 +03:00
|
|
|
self._socket.connect(address)
|
|
|
|
break # Successful connection, stop retrying to connect
|
|
|
|
except OSError as e:
|
|
|
|
# There are some errors that we know how to handle, and
|
|
|
|
# the loop will allow us to retry
|
|
|
|
if e.errno == errno.EBADF:
|
|
|
|
# Bad file descriptor, i.e. socket was closed, set it
|
|
|
|
# to none to recreate it on the next iteration
|
|
|
|
self._socket = None
|
|
|
|
else:
|
|
|
|
raise
|
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"""
|
2017-09-21 14:43:33 +03:00
|
|
|
if self._socket is None:
|
|
|
|
raise ConnectionResetError()
|
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-22 14:51:11 +03:00
|
|
|
except BrokenPipeError:
|
|
|
|
self._raise_connection_reset()
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
|
|
|
if e.errno == errno.EBADF:
|
|
|
|
self._raise_connection_reset()
|
|
|
|
else:
|
|
|
|
raise
|
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-21 14:43:33 +03:00
|
|
|
if self._socket is None:
|
|
|
|
raise ConnectionResetError()
|
|
|
|
|
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:
|
2017-09-21 14:35:06 +03:00
|
|
|
if e.errno == errno.EBADF or e.errno == errno.ENOTSOCK:
|
2017-09-03 12:54:26 +03:00
|
|
|
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.')
|