aiohttp-proxy-0.1.1+dfsg/0000755000175500017550000000000013471526507015023 5ustar debacledebacleaiohttp-proxy-0.1.1+dfsg/aiohttp_proxy/0000755000175500017550000000000013471526507017734 5ustar debacledebacleaiohttp-proxy-0.1.1+dfsg/aiohttp_proxy/errors.py0000644000175500017550000000063013471526507021621 0ustar debacledebacle# -*- coding: utf-8 -*- class SocksError(Exception): pass class NoAcceptableAuthMethods(SocksError): pass class UnknownAuthMethod(SocksError): pass class LoginAuthenticationFailed(SocksError): pass class InvalidServerVersion(SocksError): pass class InvalidServerReply(SocksError): pass class SocksConnectionError(OSError): pass class ProxyError(Exception): pass aiohttp-proxy-0.1.1+dfsg/aiohttp_proxy/proto.py0000644000175500017550000002630213471526507021454 0ustar debacledebacle# -*- coding: utf-8 -*- import asyncio import socket import struct from enum import Enum from .errors import ( SocksConnectionError, InvalidServerReply, SocksError, InvalidServerVersion, NoAcceptableAuthMethods, LoginAuthenticationFailed, UnknownAuthMethod ) RSV = NULL = 0x00 SOCKS_VER4 = 0x04 SOCKS_VER5 = 0x05 SOCKS_CMD_CONNECT = 0x01 SOCKS_CMD_BIND = 0x02 SOCKS_CMD_UDP_ASSOCIATE = 0x03 SOCKS4_GRANTED = 0x5A SOCKS5_GRANTED = 0x00 SOCKS5_AUTH_ANONYMOUS = 0x00 SOCKS5_AUTH_UNAME_PWD = 0x02 SOCKS5_AUTH_NO_ACCEPTABLE_METHODS = 0xFF SOCKS5_ATYP_IPv4 = 0x01 SOCKS5_ATYP_DOMAIN = 0x03 SOCKS5_ATYP_IPv6 = 0x04 SOCKS4_ERRORS = { 0x5B: 'Request rejected or failed', 0x5C: 'Request rejected because SOCKS server ' 'cannot connect to identd on the client', 0x5D: 'Request rejected because the client program ' 'and identd report different user-ids' } SOCKS5_ERRORS = { 0x01: 'General SOCKS server failure', 0x02: 'Connection not allowed by ruleset', 0x03: 'Network unreachable', 0x04: 'Host unreachable', 0x05: 'Connection refused', 0x06: 'TTL expired', 0x07: 'Command not supported, or protocol error', 0x08: 'Address type not supported' } def _is_proactor(loop): # pragma: no cover try: from asyncio import ProactorEventLoop except ImportError: return False return isinstance(loop, ProactorEventLoop) def _is_uvloop(loop): # pragma: no cover try: # noinspection PyPackageRequirements from uvloop import Loop except ImportError: return False return isinstance(loop, Loop) class ProxyType(Enum): SOCKS4 = 'socks4' SOCKS5 = 'socks5' HTTP = 'http' HTTPS = 'https' def is_http(self): return self.value in ['http', 'https'] def __str__(self): return self.name.lower() class BaseSocketWrapper(object): def __init__(self, loop, host, port, family=socket.AF_INET): self._loop = loop self._socks_host = host self._socks_port = port self._dest_host = None self._dest_port = None self._family = family self._socket = None async def _send(self, request): data = bytearray() for item in request: if isinstance(item, int): data.append(item) elif isinstance(item, (bytearray, bytes)): data += item else: raise ValueError('Unsupported item') await self._loop.sock_sendall(self._socket, data) async def _receive(self, n): data = b'' while len(data) < n: packet = await self._loop.sock_recv(self._socket, n - len(data)) if not packet: raise InvalidServerReply('Not all data available') data += packet return bytearray(data) async def _resolve_addr(self, host, port): addresses = await self._loop.getaddrinfo( host=host, port=port, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP, flags=socket.AI_ADDRCONFIG) if not addresses: raise OSError('Can`t resolve address %s:%s' % (host, port)) family = addresses[0][0] addr = addresses[0][4][0] return family, addr async def negotiate(self): raise NotImplementedError async def connect(self, address): self._dest_host = address[0] self._dest_port = address[1] self._socket = socket.socket( family=self._family, type=socket.SOCK_STREAM ) self._socket.setblocking(False) try: await self._loop.sock_connect( sock=self._socket, address=(self._socks_host, self._socks_port) ) except OSError as e: self.close() raise SocksConnectionError( e.errno, 'Can not connect to proxy %s:%d [%s]' % (self._socks_host, self._socks_port, e.strerror)) from e except asyncio.CancelledError: # pragma: no cover self.close() raise try: await self.negotiate() except SocksError: self.close() raise except asyncio.CancelledError: # pragma: no cover if _is_proactor(self._loop) or _is_uvloop(self._loop): self.close() raise def close(self): self._socket.close() async def sendall(self, data): await self._loop.sock_sendall(self._socket, data) async def recv(self, nbytes): return await self._loop.sock_recv(self._socket, nbytes) @property def socket(self): return self._socket class Socks4SocketWrapper(BaseSocketWrapper): def __init__(self, loop, host, port, user_id=None, rdns=False): super().__init__( loop=loop, host=host, port=port, family=socket.AF_INET ) self._user_id = user_id self._rdns = rdns async def _socks_connect(self): host, port = self._dest_host, self._dest_port port_bytes = struct.pack(b'>H', port) include_hostname = False try: # destination address provided is an IP address host_bytes = socket.inet_aton(host) except socket.error: # not IP address, probably a DNS name if self._rdns: # remote resolve (SOCKS4a) host_bytes = bytes([NULL, NULL, NULL, 0x01]) include_hostname = True else: # resolve locally family, host = await self._resolve_addr(host, port) host_bytes = socket.inet_aton(host) # build and send connect command req = [SOCKS_VER4, SOCKS_CMD_CONNECT, port_bytes, host_bytes] if self._user_id: req.append(self._user_id.encode()) req.append(NULL) if include_hostname: req += [host.encode('idna'), NULL] await self._send(req) res = await self._receive(8) if res[0] != NULL: raise InvalidServerReply('SOCKS4 proxy server sent invalid data') if res[1] != SOCKS4_GRANTED: error = SOCKS4_ERRORS.get(res[1], 'Unknown error') raise SocksError('[Errno {0:#04x}]: {1}'.format(res[1], error)) binded_addr = ( socket.inet_ntoa(res[4:]), struct.unpack('>H', res[2:4])[0] ) return (host, port), binded_addr async def negotiate(self): await self._socks_connect() class Socks5SocketWrapper(BaseSocketWrapper): def __init__(self, loop, host, port, username=None, password=None, rdns=True, family=socket.AF_INET): super().__init__( loop=loop, host=host, port=port, family=family ) self._username = username self._password = password self._rdns = rdns async def _socks_auth(self): # send auth methods if self._username and self._password: auth_methods = [SOCKS5_AUTH_UNAME_PWD, SOCKS5_AUTH_ANONYMOUS] else: auth_methods = [SOCKS5_AUTH_ANONYMOUS] req = [SOCKS_VER5, len(auth_methods)] + auth_methods await self._send(req) res = await self._receive(2) ver, auth_method = res[0], res[1] if ver != SOCKS_VER5: raise InvalidServerVersion( 'Unexpected SOCKS version number: %s' % ver ) if auth_method == SOCKS5_AUTH_NO_ACCEPTABLE_METHODS: raise NoAcceptableAuthMethods( 'No acceptable authentication methods were offered' ) if auth_method not in auth_methods: raise UnknownAuthMethod( 'Unexpected SOCKS authentication method: %s' % auth_method ) # authenticate if auth_method == SOCKS5_AUTH_UNAME_PWD: req = [0x01, chr(len(self._username)).encode(), self._username.encode(), chr(len(self._password)).encode(), self._password.encode()] await self._send(req) res = await self._receive(2) ver, status = res[0], res[1] if ver != 0x01: raise InvalidServerReply('Invalid authentication response') if status != SOCKS5_GRANTED: raise LoginAuthenticationFailed( 'Username and password authentication failure' ) async def _socks_connect(self): req_addr, resolved_addr = await self._build_dest_address() req = [SOCKS_VER5, SOCKS_CMD_CONNECT, RSV] + req_addr await self._send(req) res = await self._receive(3) ver, err_code, reserved = res[0], res[1], res[2] if ver != SOCKS_VER5: raise InvalidServerVersion( 'Unexpected SOCKS version number: %s' % ver ) if err_code != 0x00: raise SocksError(SOCKS5_ERRORS.get(err_code, 'Unknown error')) if reserved != 0x00: raise InvalidServerReply('The reserved byte must be 0x00') binded_addr = await self._read_binded_address() return resolved_addr, binded_addr async def _build_dest_address(self): host = self._dest_host port = self._dest_port family_to_byte = {socket.AF_INET: SOCKS5_ATYP_IPv4, socket.AF_INET6: SOCKS5_ATYP_IPv6} port_bytes = struct.pack('>H', port) # destination address provided is an IPv4 or IPv6 address for family in (socket.AF_INET, socket.AF_INET6): try: host_bytes = socket.inet_pton(family, host) req = [family_to_byte[family], host_bytes, port_bytes] return req, (host, port) except socket.error: pass # not IP address, probably a DNS name if self._rdns: # resolve remotely host_bytes = host.encode('idna') req = [SOCKS5_ATYP_DOMAIN, chr(len(host_bytes)).encode(), host_bytes, port_bytes] else: # resolve locally family, addr = await self._resolve_addr(host=host, port=port) host_bytes = socket.inet_pton(family, addr) req = [family_to_byte[family], host_bytes, port_bytes] host = socket.inet_ntop(family, host_bytes) return req, (host, port) async def _read_binded_address(self): atype = (await self._receive(1))[0] if atype == SOCKS5_ATYP_IPv4: addr = await self._receive(4) addr = socket.inet_ntoa(addr) elif atype == SOCKS5_ATYP_DOMAIN: length = await self._receive(1) addr = await self._receive(ord(length)) elif atype == SOCKS5_ATYP_IPv6: addr = await self._receive(16) addr = socket.inet_ntop(socket.AF_INET6, addr) else: raise InvalidServerReply('SOCKS5 proxy server sent invalid data') port = await self._receive(2) port = struct.unpack('>H', port)[0] return addr, port async def negotiate(self): await self._socks_auth() await self._socks_connect() aiohttp-proxy-0.1.1+dfsg/aiohttp_proxy/__init__.py0000644000175500017550000000120013471526507022036 0ustar debacledebacle# -*- coding: utf-8 -*- from .connector import ProxyConnector from .errors import ( SocksError, NoAcceptableAuthMethods, UnknownAuthMethod, LoginAuthenticationFailed, InvalidServerVersion, InvalidServerReply, SocksConnectionError ) from .helpers import open_connection, create_connection from .proto import ProxyType __version__ = '0.1.1' __all__ = ('ProxyConnector', 'ProxyType', 'SocksError', 'NoAcceptableAuthMethods', 'UnknownAuthMethod', 'LoginAuthenticationFailed', 'InvalidServerVersion', 'InvalidServerReply', 'SocksConnectionError', 'open_connection', 'create_connection') aiohttp-proxy-0.1.1+dfsg/aiohttp_proxy/connector.py0000644000175500017550000000567613471526507022316 0ustar debacledebacle# -*- coding: utf-8 -*- import socket from aiohttp import TCPConnector from aiohttp.abc import AbstractResolver from yarl import URL from .helpers import create_socket_wrapper, parse_proxy_url from .proto import ProxyType class NoResolver(AbstractResolver): async def resolve(self, host, port=0, family=socket.AF_INET): return [{'hostname': host, 'host': host, 'port': port, 'family': family, 'proto': 0, 'flags': 0}] async def close(self): pass # pragma: no cover class ProxyConnector(TCPConnector): def __init__(self, proxy_type=ProxyType.HTTP, host=None, port=None, username=None, password=None, rdns=False, family=socket.AF_INET, **kwargs): if rdns: kwargs['resolver'] = NoResolver() super().__init__(**kwargs) self._proxy_type = proxy_type self._proxy_host = host self._proxy_port = port self._proxy_username = username self._proxy_password = password self._rdns = rdns self._proxy_family = family @property def proxy_url(self): if self._proxy_username: url = '{scheme}://{host}:{port}'.format( scheme=self._proxy_type, host=self._proxy_host, port=self._proxy_port) else: url = '{scheme}://{host}:{port}'.format( scheme=self._proxy_type, host=self._proxy_host, port=self._proxy_port) return URL(url) # noinspection PyMethodOverriding async def _wrap_create_connection( self, protocol_factory, host=None, port=None, *args, **kwargs): if not self._proxy_type.is_http(): sock = create_socket_wrapper( loop=self._loop, proxy_type=self._proxy_type, host=self._proxy_host, port=self._proxy_port, username=self._proxy_username, password=self._proxy_password, rdns=self._rdns, family=self._proxy_family) await sock.connect((host, port)) return await super()._wrap_create_connection( protocol_factory, None, None, *args, sock=sock.socket, **kwargs) else: return await super(ProxyConnector, self)._wrap_create_connection( protocol_factory, host, port, *args, **kwargs) async def connect(self, req, traces, timeout): if self._proxy_type.is_http(): req.update_proxy(self.proxy_url.with_scheme('http'), None, req.proxy_headers) return await super(ProxyConnector, self).connect( req=req, traces=traces, timeout=timeout) @classmethod def from_url(cls, url, **kwargs): proxy_type, host, port, username, password = parse_proxy_url(url) return cls(proxy_type=proxy_type, host=host, port=port, username=username, password=password, **kwargs) aiohttp-proxy-0.1.1+dfsg/aiohttp_proxy/helpers.py0000644000175500017550000000731313471526507021754 0ustar debacledebacle# -*- coding: utf-8 -*- import asyncio import socket from urllib.parse import unquote from yarl import URL from aiohttp_proxy.errors import ProxyError from .proto import Socks4SocketWrapper, Socks5SocketWrapper, ProxyType def create_socket_wrapper(loop, proxy_type, host=None, port=None, username=None, password=None, rdns=True, family=socket.AF_INET): if proxy_type == ProxyType.SOCKS4: return Socks4SocketWrapper( loop=loop, host=host, port=port, user_id=username, rdns=rdns) elif proxy_type == ProxyType.SOCKS5: return Socks5SocketWrapper( loop=loop, host=host, port=port, username=username, password=password, rdns=rdns, family=family) else: return None def parse_proxy_url(raw_url): url = URL(raw_url) proxy_type = ProxyType(url.scheme) host = url.host if not host: raise ValueError('Empty host component') # pragma: no cover try: port = int(url.port) except TypeError: # pragma: no cover raise ValueError('Invalid port component') try: username, password = unquote(url.user), unquote(url.password) except TypeError: username, password = '', '' return proxy_type, host, port, username, password async def open_connection(socks_url=None, host=None, port=None, *, proxy_type=ProxyType.SOCKS5, socks_host='127.0.0.1', socks_port=1080, username=None, password=None, rdns=True, family=socket.AF_INET, loop=None, **kwargs): if host is None or port is None: raise ValueError('host and port must be specified') # pragma: no cover if loop is None: loop = asyncio.get_event_loop() if socks_url is not None: proxy_type, socks_host, socks_port, username, password \ = parse_proxy_url(socks_url) sock = create_socket_wrapper( loop=loop, proxy_type=proxy_type, host=socks_host, port=socks_port, username=username, password=password, rdns=rdns, family=family) if not sock: raise ProxyError( 'Only socks proxies are allowed to use `open_connection`') await sock.connect((host, port)) return await asyncio.open_connection( loop=loop, sock=sock.socket, **kwargs) async def create_connection(socks_url=None, protocol_factory=None, host=None, port=None, *, proxy_type=ProxyType.SOCKS5, socks_host='127.0.0.1', socks_port=1080, username=None, password=None, rdns=True, family=socket.AF_INET, loop=None, **kwargs): if protocol_factory is None: raise ValueError('protocol_factory ' 'must be specified') # pragma: no cover if host is None or port is None: raise ValueError('host and port ' 'must be specified') # pragma: no cover if loop is None: loop = asyncio.get_event_loop() if socks_url is not None: proxy_type, socks_host, socks_port, username, password \ = parse_proxy_url(socks_url) sock = create_socket_wrapper( loop=loop, proxy_type=proxy_type, host=socks_host, port=socks_port, username=username, password=password, rdns=rdns, family=family) if not sock: raise ProxyError( 'Only socks proxies are allowed to use `create_connection`') await sock.connect((host, port)) return await loop.create_connection( protocol_factory=protocol_factory, sock=sock.socket, **kwargs) aiohttp-proxy-0.1.1+dfsg/.travis.yml0000644000175500017550000000067113471526507017140 0ustar debacledebacledist: xenial sudo: false language: python python: - "3.5" - "3.6" env: - SKIP_IPV6_TESTS=true before_install: - chmod +x $TRAVIS_BUILD_DIR/tests/3proxy/bin/linux/3proxy install: - pip install -r requirements-dev.txt - pip install -e . script: - flake8 aiohttp_proxy tests - pytest --cov=./aiohttp_proxy tests/ -s after_success: - coveralls cache: directories: - $HOME/.cache/pip notifications: email: false aiohttp-proxy-0.1.1+dfsg/requirements-dev.txt0000644000175500017550000000017213471526507021063 0ustar debacledebacleflake8>=3.6.0 psutil>=5.4.8 pytest>=4.0.0 pytest-asyncio>=0.9.0 coverage>=4.5.2 pytest-cov>=2.6.0 coveralls>=1.5.1 aiohttp-proxy-0.1.1+dfsg/README.md0000644000175500017550000000441013471526507016301 0ustar debacledebacle## aiohttp-proxy [![Build Status](https://travis-ci.org/Skactor/aiohttp-proxy.svg?branch=master)](https://github.com/Skactor/aiohttp-proxy) [![Coverage Status](https://coveralls.io/repos/github/Skactor/aiohttp-proxy/badge.svg?branch=master)](https://coveralls.io/Skactor/aiohttp-proxy?branch=master) [![PyPI version](https://badge.fury.io/py/aiohttp-proxy.svg)](https://badge.fury.io/py/aiohttp-proxy) SOCKS proxy connector for [aiohttp](https://github.com/aio-libs/aiohttp). HTTP, HTTPS, SOCKS4(a) and SOCKS5(h) proxies are supported. ## Requirements - Python >= 3.5.3 - aiohttp >= 2.3.2 # including v3.x ## Installation ``` pip install aiohttp_proxy ``` ## Usage #### aiohttp usage: ```python import aiohttp from aiohttp_proxy import ProxyConnector, ProxyType async def fetch(url): connector = ProxyConnector.from_url('http://user:password@127.0.0.1:1080') ### or use ProxyConnector constructor # connector = ProxyConnector( # proxy_type=ProxyType.SOCKS5, # host='127.0.0.1', # port=1080, # username='user', # password='password', # rdns=True # ) async with aiohttp.ClientSession(connector=connector) as session: async with session.get(url) as response: return await response.text() ``` #### aiohttp-socks also provides `open_connection` and `create_connection` functions: ```python from aiohttp_proxy import open_connection async def fetch(): reader, writer = await open_connection( socks_url='http://user:password@127.0.0.1:1080', host='check-host.net', port=80 ) request = (b"GET /ip HTTP/1.1\r\n" b"Host: check-host.net\r\n" b"Connection: close\r\n\r\n") writer.write(request) return await reader.read(-1) ``` ## Why give aiohttp a new proxy support First must declare, our code is based on [aiohttp-socks](https://github.com/romis2012/aiohttp-socks), thank you very much for the hard work. But in order to more flexible support for multiple proxy methods (not just SOCKS proxy), we decided to fork [aiohttp-socks] (https://github.com/romis2012/aiohttp-socks), which is currently based on it. Combine with native aiohttp to provide HTTP/HTTPS proxy instead of writing troublesome discriminating code based on the type of proxy.aiohttp-proxy-0.1.1+dfsg/LICENSE.txt0000644000175500017550000002613513471526507016655 0ustar debacledebacle Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. aiohttp-proxy-0.1.1+dfsg/.gitignore0000644000175500017550000000051713471526507017016 0ustar debacledebacle*.bak *.egg *.egg-info *.eggs *.pyc *.pyd *.pyo *.so *.tar.gz *~ .DS_Store .Python .cache .coverage .coverage.* .idea .installed.cfg .noseids .tox .vimrc # bin build cover coverage develop-eggs dist docs/_build/ eggs include/ lib/ man/ nosetests.xml parts pyvenv sources var/* venv virtualenv.py .install-deps .develop .idea/ usage*.pyaiohttp-proxy-0.1.1+dfsg/setup.py0000644000175500017550000000225313471526507016537 0ustar debacledebacle#!/usr/bin/env python import codecs import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup version = None with codecs.open(os.path.join(os.path.abspath(os.path.dirname( __file__)), 'aiohttp_proxy', '__init__.py'), 'r', 'latin1') as fp: try: version = re.findall(r"^__version__ = '([^']+)'\r?$", fp.read(), re.M)[0] except IndexError: raise RuntimeError('Unable to determine version.') if sys.version_info < (3, 5, 3): raise RuntimeError("aiohttp_proxy requires Python 3.5.3+") with open('README.md') as f: long_description = f.read() setup( name='aiohttp_proxy', author='Skactor', author_email='sk4ct0r@gmail.com', version=version, license='Apache 2', url='https://github.com/Skactor/aiohttp-proxy', description='Full-featured proxy connector for aiohttp', long_description=long_description, long_description_content_type='text/markdown', packages=['aiohttp_proxy'], keywords='asyncio aiohttp socks socks5 socks4 http https proxy', install_requires=[ 'aiohttp>=2.3.2', 'yarl' ], ) aiohttp-proxy-0.1.1+dfsg/MANIFEST.in0000644000175500017550000000005713471526507016563 0ustar debacledebacle# Include the license file include LICENSE.txt aiohttp-proxy-0.1.1+dfsg/tests/0000755000175500017550000000000013663561473016171 5ustar debacledebacleaiohttp-proxy-0.1.1+dfsg/tests/conftest.py0000644000175500017550000000306313471526507020366 0ustar debacledebacleimport platform import os # noinspection PyPackageRequirements import pytest from tests.utils import resolve_path, ProxyServer LOGIN = 'admin' PASSWORD = 'admin' SOCKS5_IPV6_HOST = '::1' SOCKS5_IPV6_PORT = 7780 SOCKS5_IPV4_HOST = '127.0.0.1' SOCKS5_IPV4_PORT = 7780 SOCKS4_HOST = '127.0.0.1' SOCKS4_PORT = 7781 SKIP_IPV6_TESTS = 'SKIP_IPV6_TESTS' in os.environ @pytest.fixture(scope='session', autouse=True) def proxy_server(): system = platform.system().lower() config_path = resolve_path('./3proxy/cfg/3proxy.cfg') binary_path = resolve_path('./3proxy/bin/%s/3proxy' % system) with open(config_path, mode='w') as cfg: cfg.write('users %s:CL:%s\n' % (LOGIN, PASSWORD)) if not SKIP_IPV6_TESTS: cfg.write('auth strong\n') cfg.write('socks -p%d -i%s\n' % (SOCKS5_IPV6_PORT, SOCKS5_IPV6_HOST)) cfg.write('auth strong\n') cfg.write('socks -p%d -i%s\n' % (SOCKS5_IPV4_PORT, SOCKS5_IPV4_HOST)) cfg.write('auth none\n') cfg.write('socks -p%d -i%s\n' % (SOCKS4_PORT, SOCKS4_HOST)) server = ProxyServer(binary_path=binary_path, config_path=config_path) if not SKIP_IPV6_TESTS: server.wait_until_connectable(host=SOCKS5_IPV6_HOST, port=SOCKS5_IPV6_PORT) server.wait_until_connectable(host=SOCKS5_IPV4_HOST, port=SOCKS5_IPV4_PORT) server.wait_until_connectable(host=SOCKS4_HOST, port=SOCKS4_PORT) yield None server.kill() aiohttp-proxy-0.1.1+dfsg/tests/test_socks.py0000644000175500017550000001330113471526507020716 0ustar debacledebacleimport asyncio import socket import ssl import aiohttp # noinspection PyPackageRequirements import pytest from aiohttp_proxy import ( ProxyConnector, ProxyType, SocksError, open_connection, SocksConnectionError, create_connection) from tests.conftest import ( SOCKS5_IPV4_HOST, SOCKS5_IPV4_PORT, LOGIN, PASSWORD, SOCKS5_IPV6_HOST, SOCKS5_IPV6_PORT, SOCKS4_HOST, SOCKS4_PORT, SKIP_IPV6_TESTS) HTTP_TEST_HOST = 'httpbin.org' HTTP_TEST_PORT = 80 HTTPS_TEST_HOST = 'httpbin.org' HTTPS_TEST_PORT = 443 HTTP_TEST_URL = 'http://%s/ip' % HTTP_TEST_HOST HTTPS_TEST_URL = 'https://%s/ip' % HTTP_TEST_HOST HTTP_URL_DELAY_3_SEC = 'http://httpbin.org/delay/3' HTTP_URL_REDIRECT = 'http://httpbin.org/redirect/1' SOCKS5_IPV4_URL = 'socks5://{LOGIN}:{PASSWORD}@{SOCKS5_IPV4_HOST}:{SOCKS5_IPV4_PORT}'.format( # noqa SOCKS5_IPV4_HOST=SOCKS5_IPV4_HOST, SOCKS5_IPV4_PORT=SOCKS5_IPV4_PORT, LOGIN=LOGIN, PASSWORD=PASSWORD, ) SOCKS5_IPV6_URL = 'socks5://{LOGIN}:{PASSWORD}@{SOCKS5_IPV6_HOST}:{SOCKS5_IPV6_PORT}'.format( # noqa SOCKS5_IPV6_HOST='[%s]' % SOCKS5_IPV6_HOST, SOCKS5_IPV6_PORT=SOCKS5_IPV6_PORT, LOGIN=LOGIN, PASSWORD=PASSWORD, ) SOCKS4_URL = 'socks4://{SOCKS4_HOST}:{SOCKS4_PORT}'.format( SOCKS4_HOST=SOCKS4_HOST, SOCKS4_PORT=SOCKS4_PORT, ) @pytest.mark.parametrize('url', (HTTP_TEST_URL, HTTPS_TEST_URL)) @pytest.mark.parametrize('rdns', (True, False)) @pytest.mark.asyncio async def test_socks5_connector_ipv4(url, rdns): connector = ProxyConnector.from_url(SOCKS5_IPV4_URL, rdns=rdns) async with aiohttp.ClientSession(connector=connector) as session: async with session.get(url) as resp: assert resp.status == 200 @pytest.mark.asyncio async def test_socks5_connector_with_invalid_credentials(): connector = ProxyConnector( proxy_type=ProxyType.SOCKS5, host=SOCKS5_IPV4_HOST, port=SOCKS5_IPV4_PORT, username=LOGIN, password=PASSWORD + 'aaa', ) with pytest.raises(SocksError): async with aiohttp.ClientSession(connector=connector) as session: async with session.get(HTTP_TEST_URL) as resp: await resp.text() @pytest.mark.asyncio async def test_socks5_connector_with_timeout(): connector = ProxyConnector( proxy_type=ProxyType.SOCKS5, host=SOCKS5_IPV4_HOST, port=SOCKS5_IPV4_PORT, username=LOGIN, password=PASSWORD, ) with pytest.raises(asyncio.TimeoutError): async with aiohttp.ClientSession(connector=connector) as session: async with session.get(HTTP_URL_DELAY_3_SEC, timeout=1) as resp: await resp.text() @pytest.mark.asyncio async def test_socks5_connector_with_invalid_proxy_port(unused_tcp_port): connector = ProxyConnector( proxy_type=ProxyType.SOCKS5, host=SOCKS5_IPV4_HOST, port=unused_tcp_port, username=LOGIN, password=PASSWORD, ) with pytest.raises(SocksConnectionError): async with aiohttp.ClientSession(connector=connector) as session: async with session.get(HTTP_TEST_URL) as resp: await resp.text() @pytest.mark.skipif(SKIP_IPV6_TESTS, reason='TravisCI doesn`t support ipv6') @pytest.mark.asyncio async def test_socks5_connector_ipv6(): connector = ProxyConnector.from_url(SOCKS5_IPV6_URL, family=socket.AF_INET6) async with aiohttp.ClientSession(connector=connector) as session: async with session.get(HTTP_TEST_URL) as resp: assert resp.status == 200 @pytest.mark.parametrize('url', (HTTP_TEST_URL, HTTPS_TEST_URL)) @pytest.mark.parametrize('rdns', (True, False)) @pytest.mark.asyncio async def test_socks4_connector(url, rdns): connector = ProxyConnector.from_url(SOCKS4_URL, rdns=rdns, ) async with aiohttp.ClientSession(connector=connector) as session: async with session.get(url) as resp: assert resp.status == 200 @pytest.mark.parametrize('rdns', (True, False)) @pytest.mark.asyncio async def test_socks5_http_open_connection(rdns): reader, writer = await open_connection( socks_url=SOCKS5_IPV4_URL, host=HTTP_TEST_HOST, port=HTTP_TEST_PORT, rdns=rdns, ) request = ("GET /ip HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n\r\n" % HTTP_TEST_HOST) writer.write(request.encode()) response = await reader.read(-1) assert b'200 OK' in response @pytest.mark.parametrize('rdns', (True, False)) @pytest.mark.asyncio async def test_socks5_https_open_connection(rdns): reader, writer = await open_connection( socks_url=SOCKS5_IPV4_URL, host=HTTPS_TEST_HOST, port=HTTPS_TEST_PORT, ssl=ssl.create_default_context(), server_hostname=HTTPS_TEST_HOST, rdns=rdns, ) request = ("GET /ip HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n\r\n" % HTTPS_TEST_HOST) writer.write(request.encode()) response = await reader.read(-1) assert b'200 OK' in response @pytest.mark.asyncio async def test_socks5_http_create_connection(event_loop): reader = asyncio.StreamReader(loop=event_loop) protocol = asyncio.StreamReaderProtocol(reader, loop=event_loop) transport, _ = await create_connection( socks_url=SOCKS5_IPV4_URL, protocol_factory=lambda: protocol, host=HTTP_TEST_HOST, port=HTTP_TEST_PORT, ) writer = asyncio.StreamWriter(transport, protocol, reader, event_loop) request = ("GET /ip HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n\r\n" % HTTP_TEST_HOST) writer.write(request.encode()) response = await reader.read(-1) assert b'200 OK' in response aiohttp-proxy-0.1.1+dfsg/tests/utils.py0000644000175500017550000000275013471526507017703 0ustar debacledebacleimport socket import subprocess import time import os def is_connectable(host, port): sock = None try: sock = socket.create_connection((host, port), 1) result = True except socket.error: result = False finally: if sock: sock.close() return result def resolve_path(path): return os.path.normpath( os.path.join(os.path.dirname(os.path.realpath(__file__)), path)) class ProxyServer(object): def __init__(self, binary_path, config_path): self.process = subprocess.Popen([binary_path, config_path], shell=False) def wait_until_connectable(self, host, port, timeout=10): count = 0 while not is_connectable(host=host, port=port): if self.process.poll() is not None: # process has exited raise Exception( 'The process appears to have exited ' 'before we could connect.') if count >= timeout: self.kill() raise Exception( 'The proxy server has not binded ' 'to (%s, %s) in %d seconds' % (host, port, timeout)) count += 1 time.sleep(1) return True def kill(self): if self.process: self.process.terminate() self.process.kill() self.process.wait() aiohttp-proxy-0.1.1+dfsg/tests/__init__.py0000644000175500017550000000003113471526507020270 0ustar debacledebacle# -*- coding: utf-8 -*-