2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
This module holds a rough implementation of the C# TCP client.
|
|
|
|
"""
|
2017-09-04 18:18:33 +03:00
|
|
|
import errno
|
2016-08-26 13:58:53 +03:00
|
|
|
import socket
|
2018-01-05 20:31:48 +03:00
|
|
|
import time
|
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
|
|
|
|
2018-01-05 20:31:48 +03:00
|
|
|
MAX_TIMEOUT = 15 # in seconds
|
|
|
|
CONN_RESET_ERRNOS = {
|
|
|
|
errno.EBADF, errno.ENOTSOCK, errno.ENETUNREACH,
|
|
|
|
errno.EINVAL, errno.ENOTCONN
|
|
|
|
}
|
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
class TcpClient:
|
2017-11-26 19:14:28 +03:00
|
|
|
"""A simple TCP client to ease the work with sockets and proxies."""
|
2017-09-02 20:33:42 +03:00
|
|
|
def __init__(self, proxy=None, timeout=timedelta(seconds=5)):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
Initializes the TCP client.
|
|
|
|
|
|
|
|
:param proxy: the proxy to be used, if any.
|
|
|
|
:param timeout: the timeout for connect, read and write operations.
|
|
|
|
"""
|
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:
|
2017-12-28 02:22:28 +03:00
|
|
|
raise TypeError('Invalid timeout type: {}'.format(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-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
Tries connecting forever to IP:port unless an OSError is raised.
|
|
|
|
|
|
|
|
:param ip: the IP to connect to.
|
|
|
|
:param port: the port to connect to.
|
2017-06-22 20:21:33 +03:00
|
|
|
"""
|
2017-09-21 13:37:05 +03:00
|
|
|
if ':' in ip: # IPv6
|
2018-01-26 16:38:13 +03:00
|
|
|
ip = ip.replace('[', '').replace(']', '')
|
2017-09-21 13:37:05 +03:00
|
|
|
mode, address = socket.AF_INET6, (ip, port, 0, 0)
|
|
|
|
else:
|
|
|
|
mode, address = socket.AF_INET, (ip, port)
|
|
|
|
|
2018-01-05 20:31:48 +03:00
|
|
|
timeout = 1
|
2017-09-21 13:37:05 +03:00
|
|
|
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
|
2018-01-08 14:26:32 +03:00
|
|
|
if e.errno in (errno.EBADF, errno.ENOTSOCK, errno.EINVAL,
|
|
|
|
errno.ECONNREFUSED):
|
2017-09-21 13:37:05 +03:00
|
|
|
# Bad file descriptor, i.e. socket was closed, set it
|
|
|
|
# to none to recreate it on the next iteration
|
|
|
|
self._socket = None
|
2018-01-05 20:31:48 +03:00
|
|
|
time.sleep(timeout)
|
|
|
|
timeout = min(timeout * 2, MAX_TIMEOUT)
|
2017-09-21 13:37:05 +03:00
|
|
|
else:
|
|
|
|
raise
|
2017-08-29 14:35:56 +03:00
|
|
|
|
|
|
|
def _get_connected(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Determines whether the client is connected or not."""
|
2017-11-14 14:01:33 +03:00
|
|
|
return self._socket is not None and self._socket.fileno() >= 0
|
2017-08-29 14:35:56 +03:00
|
|
|
|
|
|
|
connected = property(fget=_get_connected)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def close(self):
|
2017-11-26 19:14:28 +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):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
Writes (sends) the specified bytes to the connected peer.
|
|
|
|
|
|
|
|
:param data: the data to send.
|
|
|
|
"""
|
2017-09-21 14:43:33 +03:00
|
|
|
if self._socket is None:
|
2018-01-05 20:31:48 +03:00
|
|
|
self._raise_connection_reset()
|
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-12-22 22:45:23 +03:00
|
|
|
except ConnectionError:
|
2017-09-22 14:51:11 +03:00
|
|
|
self._raise_connection_reset()
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
2018-01-05 20:31:48 +03:00
|
|
|
if e.errno in CONN_RESET_ERRNOS:
|
2017-09-03 12:54:26 +03:00
|
|
|
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-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
Reads (receives) a whole block of size bytes from the connected peer.
|
2017-06-09 12:42:39 +03:00
|
|
|
|
2017-11-26 19:14:28 +03:00
|
|
|
:param size: the size of the block to be read.
|
|
|
|
:return: the read data with len(data) == size.
|
2017-06-09 12:42:39 +03:00
|
|
|
"""
|
2017-09-21 14:43:33 +03:00
|
|
|
if self._socket is None:
|
2018-01-05 20:31:48 +03:00
|
|
|
self._raise_connection_reset()
|
2017-09-21 14:43:33 +03:00
|
|
|
|
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-12-22 22:45:23 +03:00
|
|
|
except ConnectionError:
|
2017-12-22 13:27:57 +03:00
|
|
|
self._raise_connection_reset()
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
2018-01-05 20:31:48 +03:00
|
|
|
if e.errno in CONN_RESET_ERRNOS:
|
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):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Disconnects the client and raises ConnectionResetError."""
|
2017-09-03 12:54:26 +03:00
|
|
|
self.close() # Connection reset -> flag as socket closed
|
|
|
|
raise ConnectionResetError('The server has closed the connection.')
|