2016-08-28 14:43:00 +03:00
|
|
|
# Python rough implementation of a C# TCP client
|
2017-10-06 22:02:41 +03:00
|
|
|
import asyncio
|
2017-09-04 18:18:33 +03:00
|
|
|
import errno
|
2016-08-26 13:58:53 +03:00
|
|
|
import socket
|
2017-11-16 17:31:39 +03:00
|
|
|
import logging
|
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
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2017-10-22 20:13:45 +03:00
|
|
|
MAX_TIMEOUT = 15 # in seconds
|
|
|
|
CONN_RESET_ERRNOS = {
|
|
|
|
errno.EBADF, errno.ENOTSOCK, errno.ENETUNREACH,
|
2017-11-15 13:30:44 +03:00
|
|
|
errno.EINVAL, errno.ENOTCONN, errno.EHOSTUNREACH,
|
|
|
|
errno.ECONNREFUSED, errno.ECONNRESET, errno.ECONNABORTED,
|
|
|
|
errno.ENETDOWN, errno.ENETRESET, errno.ECONNABORTED,
|
2017-11-16 02:56:57 +03:00
|
|
|
errno.EHOSTDOWN, errno.EPIPE, errno.ESHUTDOWN
|
2017-10-22 20:13:45 +03:00
|
|
|
}
|
2017-11-16 02:56:57 +03:00
|
|
|
# catched: EHOSTUNREACH, ECONNREFUSED, ECONNRESET, ENETUNREACH
|
|
|
|
# ConnectionError: EPIPE, ESHUTDOWN, ECONNABORTED, ECONNREFUSED, ECONNRESET
|
2017-10-22 20:13:45 +03:00
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
class TcpClient:
|
2017-10-22 15:06:36 +03:00
|
|
|
def __init__(self, proxy=None, timeout=timedelta(seconds=5), loop=None):
|
2017-09-22 17:11:07 +03:00
|
|
|
self.proxy = proxy
|
2017-08-29 14:35:56 +03:00
|
|
|
self._socket = None
|
2017-10-22 15:06:36 +03:00
|
|
|
self._loop = loop if loop else asyncio.get_event_loop()
|
2017-11-16 17:31:39 +03:00
|
|
|
self._logger = logging.getLogger(__name__)
|
2017-09-13 10:44:58 +03:00
|
|
|
|
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-10-22 15:06:36 +03:00
|
|
|
self._socket.setblocking(False)
|
2017-09-21 13:37:05 +03:00
|
|
|
|
2017-10-06 22:02:41 +03:00
|
|
|
async 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)
|
|
|
|
|
2017-10-22 15:06:36 +03:00
|
|
|
timeout = 1
|
2017-09-21 13:37:05 +03:00
|
|
|
while True:
|
|
|
|
try:
|
2017-10-22 15:06:36 +03:00
|
|
|
if not self._socket:
|
2017-09-21 13:37:05 +03:00
|
|
|
self._recreate_socket(mode)
|
2017-09-02 20:14:11 +03:00
|
|
|
|
2017-11-16 17:31:39 +03:00
|
|
|
await asyncio.wait_for(
|
|
|
|
self._loop.sock_connect(self._socket, address),
|
|
|
|
timeout=self.timeout,
|
|
|
|
loop=self._loop
|
|
|
|
)
|
2017-09-21 13:37:05 +03:00
|
|
|
break # Successful connection, stop retrying to connect
|
2017-11-16 17:31:39 +03:00
|
|
|
except asyncio.TimeoutError as e:
|
|
|
|
raise TimeoutError() from e
|
2017-09-21 13:37:05 +03:00
|
|
|
except OSError as e:
|
2017-11-16 17:31:39 +03:00
|
|
|
self._logger.debug('Connect exception: %r' % e)
|
2017-11-16 02:56:57 +03:00
|
|
|
# ConnectionError + (errno.EBADF, errno.ENOTSOCK, errno.EINVAL)
|
|
|
|
if e.errno in CONN_RESET_ERRNOS:
|
2017-09-21 13:37:05 +03:00
|
|
|
self._socket = None
|
2017-10-22 20:13:45 +03:00
|
|
|
await asyncio.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-14 13:52: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):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Closes the connection"""
|
2017-10-06 20:30:14 +03:00
|
|
|
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
|
|
|
|
2017-10-06 22:02:41 +03:00
|
|
|
async 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:
|
2017-11-14 13:52:33 +03:00
|
|
|
self._raise_connection_reset()
|
2016-09-10 11:17:15 +03:00
|
|
|
|
2017-09-02 19:49:29 +03:00
|
|
|
try:
|
2017-11-14 13:52:33 +03:00
|
|
|
await asyncio.wait_for(
|
|
|
|
self.sock_sendall(data),
|
|
|
|
timeout=self.timeout,
|
|
|
|
loop=self._loop
|
|
|
|
)
|
2017-10-22 15:06:36 +03:00
|
|
|
except asyncio.TimeoutError as e:
|
2017-09-03 11:01:00 +03:00
|
|
|
raise TimeoutError() from e
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
2017-11-16 17:31:39 +03:00
|
|
|
self._logger.debug('Write exception: %r' % e)
|
2017-10-22 20:13:45 +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-10-06 22:02:41 +03:00
|
|
|
async def read(self, size):
|
2017-06-09 12:42:39 +03:00
|
|
|
"""Reads (receives) a whole block of 'size bytes
|
|
|
|
from the connected peer.
|
|
|
|
"""
|
2017-09-21 14:43:33 +03:00
|
|
|
|
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:
|
2017-11-14 13:52:33 +03:00
|
|
|
if self._socket is None:
|
|
|
|
self._raise_connection_reset()
|
|
|
|
partial = await asyncio.wait_for(
|
|
|
|
self.sock_recv(bytes_left),
|
|
|
|
timeout=self.timeout,
|
|
|
|
loop=self._loop
|
|
|
|
)
|
2017-10-22 15:06:36 +03:00
|
|
|
except asyncio.TimeoutError as e:
|
2017-09-03 11:01:00 +03:00
|
|
|
raise TimeoutError() from e
|
2017-09-03 12:54:26 +03:00
|
|
|
except OSError as e:
|
2017-11-16 17:31:39 +03:00
|
|
|
self._logger.debug('Read exception: %r' % e)
|
2017-10-22 20:13:45 +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):
|
|
|
|
self.close() # Connection reset -> flag as socket closed
|
|
|
|
raise ConnectionResetError('The server has closed the connection.')
|
2017-11-14 13:52:33 +03:00
|
|
|
|
|
|
|
# due to new https://github.com/python/cpython/pull/4386
|
|
|
|
def sock_recv(self, n):
|
|
|
|
fut = self._loop.create_future()
|
|
|
|
self._sock_recv(fut, None, n)
|
|
|
|
return fut
|
|
|
|
|
|
|
|
def _sock_recv(self, fut, registered_fd, n):
|
|
|
|
if registered_fd is not None:
|
|
|
|
self._loop.remove_reader(registered_fd)
|
|
|
|
if fut.cancelled():
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = self._socket.recv(n)
|
|
|
|
except (BlockingIOError, InterruptedError):
|
|
|
|
fd = self._socket.fileno()
|
|
|
|
self._loop.add_reader(fd, self._sock_recv, fut, fd, n)
|
|
|
|
except Exception as exc:
|
|
|
|
fut.set_exception(exc)
|
|
|
|
else:
|
|
|
|
fut.set_result(data)
|
|
|
|
|
|
|
|
def sock_sendall(self, data):
|
|
|
|
fut = self._loop.create_future()
|
|
|
|
if data:
|
|
|
|
self._sock_sendall(fut, None, data)
|
|
|
|
else:
|
|
|
|
fut.set_result(None)
|
|
|
|
return fut
|
|
|
|
|
|
|
|
def _sock_sendall(self, fut, registered_fd, data):
|
|
|
|
if registered_fd:
|
|
|
|
self._loop.remove_writer(registered_fd)
|
|
|
|
if fut.cancelled():
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
n = self._socket.send(data)
|
|
|
|
except (BlockingIOError, InterruptedError):
|
|
|
|
n = 0
|
|
|
|
except Exception as exc:
|
|
|
|
fut.set_exception(exc)
|
|
|
|
return
|
|
|
|
|
|
|
|
if n == len(data):
|
|
|
|
fut.set_result(None)
|
|
|
|
else:
|
|
|
|
if n:
|
|
|
|
data = data[n:]
|
|
|
|
fd = self._socket.fileno()
|
|
|
|
self._loop.add_writer(fd, self._sock_sendall, fut, fd, data)
|