2017-11-26 19:14:28 +03:00
|
|
|
"""
|
|
|
|
This module holds a rough implementation of the C# TCP client.
|
2018-06-06 21:41:01 +03:00
|
|
|
|
|
|
|
This class is **not** safe across several tasks since partial reads
|
|
|
|
may be ``await``'ed before being able to return the exact byte count.
|
|
|
|
|
|
|
|
This class is also not concerned about disconnections or retries of
|
|
|
|
any sort, nor any other kind of errors such as connecting twice.
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
2018-06-06 21:41:01 +03:00
|
|
|
import asyncio
|
2018-06-14 17:08:23 +03:00
|
|
|
import errno
|
2018-02-26 15:41:07 +03:00
|
|
|
import logging
|
2016-08-26 13:58:53 +03:00
|
|
|
import socket
|
2018-07-08 18:45:49 +03:00
|
|
|
import ssl
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2018-06-14 17:08:23 +03:00
|
|
|
CONN_RESET_ERRNOS = {
|
|
|
|
errno.EBADF, errno.ENOTSOCK, errno.ENETUNREACH,
|
|
|
|
errno.EINVAL, errno.ENOTCONN, errno.EHOSTUNREACH,
|
|
|
|
errno.ECONNREFUSED, errno.ECONNRESET, errno.ECONNABORTED,
|
|
|
|
errno.ENETDOWN, errno.ENETRESET, errno.ECONNABORTED,
|
|
|
|
errno.EHOSTDOWN, errno.EPIPE, errno.ESHUTDOWN
|
|
|
|
}
|
|
|
|
# catched: EHOSTUNREACH, ECONNREFUSED, ECONNRESET, ENETUNREACH
|
|
|
|
# ConnectionError: EPIPE, ESHUTDOWN, ECONNABORTED, ECONNREFUSED, ECONNRESET
|
|
|
|
|
2018-02-20 17:58:51 +03:00
|
|
|
try:
|
|
|
|
import socks
|
|
|
|
except ImportError:
|
|
|
|
socks = None
|
|
|
|
|
2018-07-08 18:45:49 +03:00
|
|
|
SSL_PORT = 443
|
2018-02-26 15:41:07 +03:00
|
|
|
__log__ = logging.getLogger(__name__)
|
|
|
|
|
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."""
|
2018-06-14 17:08:23 +03:00
|
|
|
|
|
|
|
class SocketClosed(ConnectionError):
|
|
|
|
pass
|
|
|
|
|
2018-07-08 18:45:49 +03:00
|
|
|
def __init__(self, *, loop, timeout, ssl=None, proxy=None):
|
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.
|
2018-07-08 18:45:49 +03:00
|
|
|
:param ssl: ssl.wrap_socket keyword arguments to use when connecting
|
|
|
|
if port == SSL_PORT, or do nothing if not present.
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
2018-06-14 20:35:12 +03:00
|
|
|
self._loop = loop
|
2017-09-22 17:11:07 +03:00
|
|
|
self.proxy = proxy
|
2018-07-08 18:45:49 +03:00
|
|
|
self.ssl = ssl
|
2017-08-29 14:35:56 +03:00
|
|
|
self._socket = None
|
2018-08-29 12:35:44 +03:00
|
|
|
self._reader = None
|
|
|
|
self._writer = None
|
2018-06-14 17:08:23 +03:00
|
|
|
self._closed = asyncio.Event(loop=self._loop)
|
|
|
|
self._closed.set()
|
2017-09-13 10:44:58 +03:00
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
if isinstance(timeout, (int, float)):
|
2017-09-21 14:43:33 +03:00
|
|
|
self.timeout = float(timeout)
|
2018-06-06 21:41:01 +03:00
|
|
|
elif hasattr(timeout, 'seconds'):
|
|
|
|
self.timeout = float(timeout.seconds)
|
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
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
@staticmethod
|
|
|
|
def _create_socket(mode, proxy):
|
|
|
|
if proxy is None:
|
|
|
|
s = socket.socket(mode, socket.SOCK_STREAM)
|
2017-05-30 12:42:14 +03:00
|
|
|
else:
|
2018-07-25 03:21:44 +03:00
|
|
|
__log__.info('Connection will be made through proxy %s', proxy)
|
2017-05-30 11:40:33 +03:00
|
|
|
import socks
|
2018-06-06 21:41:01 +03:00
|
|
|
s = socks.socksocket(mode, socket.SOCK_STREAM)
|
|
|
|
if isinstance(proxy, dict):
|
|
|
|
s.set_proxy(**proxy)
|
2017-06-05 07:04:01 +03:00
|
|
|
else: # tuple, list, etc.
|
2018-06-06 21:41:01 +03:00
|
|
|
s.set_proxy(*proxy)
|
|
|
|
s.setblocking(False)
|
|
|
|
return s
|
2017-05-30 11:40:33 +03:00
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
async def connect(self, ip, port):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""
|
2018-06-14 17:08:23 +03:00
|
|
|
Tries connecting to IP:port unless an OSError is raised.
|
2017-11-26 19:14:28 +03:00
|
|
|
|
|
|
|
: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-06-14 17:08:23 +03:00
|
|
|
try:
|
|
|
|
if self._socket is None:
|
|
|
|
self._socket = self._create_socket(mode, self.proxy)
|
2018-07-19 21:38:53 +03:00
|
|
|
wrap_ssl = self.ssl and port == SSL_PORT
|
|
|
|
else:
|
|
|
|
wrap_ssl = False
|
2018-06-14 17:08:23 +03:00
|
|
|
|
|
|
|
await asyncio.wait_for(
|
|
|
|
self._loop.sock_connect(self._socket, address),
|
|
|
|
timeout=self.timeout,
|
|
|
|
loop=self._loop
|
|
|
|
)
|
2018-07-19 21:38:53 +03:00
|
|
|
if wrap_ssl:
|
2018-07-19 21:56:45 +03:00
|
|
|
# Temporarily set the socket to blocking
|
|
|
|
# (timeout) until connection is established.
|
|
|
|
self._socket.settimeout(self.timeout)
|
|
|
|
self._socket = ssl.wrap_socket(
|
|
|
|
self._socket, do_handshake_on_connect=True, **self.ssl)
|
|
|
|
self._socket.setblocking(False)
|
2018-07-19 21:38:53 +03:00
|
|
|
|
2018-06-14 17:08:23 +03:00
|
|
|
self._closed.clear()
|
2018-08-29 12:35:44 +03:00
|
|
|
self._reader, self._writer =\
|
|
|
|
await asyncio.open_connection(sock=self._socket)
|
2018-06-14 17:08:23 +03:00
|
|
|
except OSError as e:
|
|
|
|
if e.errno in CONN_RESET_ERRNOS:
|
|
|
|
raise ConnectionResetError() from e
|
|
|
|
else:
|
|
|
|
raise
|
2018-06-06 21:41:01 +03:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_connected(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Determines whether the client is connected or not."""
|
2018-06-14 17:08:23 +03:00
|
|
|
return not self._closed.is_set()
|
2017-08-29 14:35:56 +03:00
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
def close(self):
|
2017-11-26 19:14:28 +03:00
|
|
|
"""Closes the connection."""
|
2018-06-20 18:59:11 +03:00
|
|
|
fd = None
|
2018-06-14 17:08:23 +03:00
|
|
|
try:
|
2018-08-29 12:35:44 +03:00
|
|
|
if self._writer is not None:
|
|
|
|
self._writer.close()
|
|
|
|
|
2018-06-14 17:08:23 +03:00
|
|
|
if self._socket is not None:
|
2018-06-20 18:59:11 +03:00
|
|
|
fd = self._socket.fileno()
|
2018-06-14 17:08:23 +03:00
|
|
|
if self.is_connected:
|
|
|
|
self._socket.shutdown(socket.SHUT_RDWR)
|
2018-06-06 21:41:01 +03:00
|
|
|
self._socket.close()
|
2018-06-14 17:08:23 +03:00
|
|
|
except OSError:
|
|
|
|
pass # Ignore ENOTCONN, EBADF, and any other error when closing
|
|
|
|
finally:
|
|
|
|
self._socket = None
|
2018-08-29 12:35:44 +03:00
|
|
|
self._reader = None
|
|
|
|
self._writer = None
|
2018-06-14 17:08:23 +03:00
|
|
|
self._closed.set()
|
2018-06-30 14:25:59 +03:00
|
|
|
if fd and fd != -1:
|
2018-06-17 16:48:26 +03:00
|
|
|
self._loop.remove_reader(fd)
|
2018-06-14 17:08:23 +03:00
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
async 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.
|
|
|
|
"""
|
2018-06-06 21:41:01 +03:00
|
|
|
if not self.is_connected:
|
2018-06-14 17:08:23 +03:00
|
|
|
raise ConnectionResetError('Not connected')
|
2018-06-14 17:13:46 +03:00
|
|
|
|
2018-08-29 12:35:44 +03:00
|
|
|
self._writer.write(data)
|
|
|
|
await self._writer.drain()
|
2018-06-06 21:41:01 +03:00
|
|
|
|
|
|
|
async 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
|
|
|
"""
|
2018-06-06 21:41:01 +03:00
|
|
|
if not self.is_connected:
|
2018-06-14 17:08:23 +03:00
|
|
|
raise ConnectionResetError('Not connected')
|
2017-09-21 14:43:33 +03:00
|
|
|
|
2018-08-29 12:35:44 +03:00
|
|
|
return await self._reader.readexactly(size)
|