Hello community, here is the log from the commit of package python-PySocks for openSUSE:Factory checked in at 2017-12-23 12:11:56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-PySocks (Old) and /work/SRC/openSUSE:Factory/.python-PySocks.new (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-PySocks" Sat Dec 23 12:11:56 2017 rev:4 rq:559160 version:1.6.8 Changes: -------- --- /work/SRC/openSUSE:Factory/python-PySocks/python-PySocks.changes 2017-11-10 14:41:49.361868265 +0100 +++ /work/SRC/openSUSE:Factory/.python-PySocks.new/python-PySocks.changes 2017-12-23 12:11:57.837590595 +0100 @@ -1,0 +2,18 @@ +Thu Dec 21 18:26:53 UTC 2017 - [email protected] + +- specfile: + * update copyright year + +- update to version 1.6.8: + * Remove support for EOL Python 3.3 + * Make create_connection() signature match socket module + * Add python version classifiers + * Include win_inet_pton when installing on Python 2.x under Windows + * fix #937 getpeername() errror while using gevent + * Update README.md + * PEP8 fixes for line length, indentation, line breaks and other + minor issues. + * Normalize quoting. + * Update socks.py + +------------------------------------------------------------------- Old: ---- PySocks-1.6.7.tar.gz New: ---- PySocks-1.6.8.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-PySocks.spec ++++++ --- /var/tmp/diff_new_pack.AMWMSW/_old 2017-12-23 12:11:58.321566997 +0100 +++ /var/tmp/diff_new_pack.AMWMSW/_new 2017-12-23 12:11:58.321566997 +0100 @@ -20,7 +20,7 @@ %{?!python_module:%define python_module() python-%{**} python3-%{**}} %define oldpython python Name: python-PySocks -Version: 1.6.7 +Version: 1.6.8 Release: 0 Summary: A Python SOCKS client module License: BSD-3-Clause ++++++ PySocks-1.6.7.tar.gz -> PySocks-1.6.8.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/PySocks-1.6.7/PKG-INFO new/PySocks-1.6.8/PKG-INFO --- old/PySocks-1.6.7/PKG-INFO 2017-03-23 05:11:52.000000000 +0100 +++ new/PySocks-1.6.8/PKG-INFO 2017-12-21 05:25:34.000000000 +0100 @@ -1,6 +1,6 @@ -Metadata-Version: 1.0 +Metadata-Version: 1.1 Name: PySocks -Version: 1.6.7 +Version: 1.6.8 Summary: A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information. Home-page: https://github.com/Anorov/PySocks Author: Anorov @@ -9,3 +9,6 @@ Description: UNKNOWN Keywords: socks,proxy Platform: UNKNOWN +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/PySocks-1.6.7/PySocks.egg-info/PKG-INFO new/PySocks-1.6.8/PySocks.egg-info/PKG-INFO --- old/PySocks-1.6.7/PySocks.egg-info/PKG-INFO 2017-03-23 05:11:51.000000000 +0100 +++ new/PySocks-1.6.8/PySocks.egg-info/PKG-INFO 2017-12-21 05:25:34.000000000 +0100 @@ -1,6 +1,6 @@ -Metadata-Version: 1.0 +Metadata-Version: 1.1 Name: PySocks -Version: 1.6.7 +Version: 1.6.8 Summary: A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information. Home-page: https://github.com/Anorov/PySocks Author: Anorov @@ -9,3 +9,6 @@ Description: UNKNOWN Keywords: socks,proxy Platform: UNKNOWN +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/PySocks-1.6.7/README.md new/PySocks-1.6.8/README.md --- old/PySocks-1.6.7/README.md 2016-05-21 23:53:04.000000000 +0200 +++ new/PySocks-1.6.8/README.md 2017-12-21 05:05:00.000000000 +0100 @@ -1,9 +1,14 @@ PySocks ======= -Updated and semi-actively maintained version of [SocksiPy](http://socksipy.sourceforge.net/), with bug fixes and extra features. +PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of [SocksiPy](http://socksipy.sourceforge.net/) with bug fixes and extra features. -Acts as a drop-in replacement to the socket module. +Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by calling `socket_object.set_proxy()`. + +Status Update +------------- + +I no longer have the time to actively work on this project. I will gladly accept thoughtful pull requests and continue to update here and on PyPI in response to PRs, but I won't be putting in any changes of my own other than version bumps. If anyone would like to take the project off of my hands, please email me or create an issue. Thanks. ---------------- diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/PySocks-1.6.7/setup.cfg new/PySocks-1.6.8/setup.cfg --- old/PySocks-1.6.7/setup.cfg 2017-03-23 05:11:52.000000000 +0100 +++ new/PySocks-1.6.8/setup.cfg 2017-12-21 05:25:34.000000000 +0100 @@ -1,5 +1,5 @@ [egg_info] tag_date = 0 -tag_svn_revision = 0 tag_build = +tag_svn_revision = 0 diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/PySocks-1.6.7/setup.py new/PySocks-1.6.8/setup.py --- old/PySocks-1.6.7/setup.py 2017-03-23 05:08:58.000000000 +0100 +++ new/PySocks-1.6.8/setup.py 2017-12-21 05:21:04.000000000 +0100 @@ -1,7 +1,14 @@ #!/usr/bin/env python +import os +import sys from setuptools import setup -VERSION = "1.6.7" +VERSION = "1.6.8" + +requirements = [] +if os.name == "nt" and sys.version_info < (3, 0): + # Required due to missing socket.inet_ntop & socket.inet_pton method in Windows Python 2.x + requirements.append("win-inet-pton") setup( name = "PySocks", @@ -12,5 +19,11 @@ author = "Anorov", author_email = "[email protected]", keywords = ["socks", "proxy"], - py_modules=["socks", "sockshandler"] + py_modules=["socks", "sockshandler"], + install_requires=requirements, + classifiers=( + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + ) ) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/PySocks-1.6.7/socks.py new/PySocks-1.6.8/socks.py --- old/PySocks-1.6.7/socks.py 2017-03-23 05:08:58.000000000 +0100 +++ new/PySocks-1.6.8/socks.py 2017-12-21 05:05:00.000000000 +0100 @@ -1,10 +1,9 @@ -""" -SocksiPy - Python SOCKS module. +"""SocksiPy - Python SOCKS module. Copyright 2006 Dan-Haim. All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, @@ -22,7 +21,7 @@ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This module provides a standard socket-like interface for Python @@ -38,39 +37,44 @@ Modifications made by Anorov (https://github.com/Anorov) -Forked and renamed to PySocks --Fixed issue with HTTP proxy failure checking (same bug that was in the old ___recvall() method) +-Fixed issue with HTTP proxy failure checking (same bug that was in the + old ___recvall() method) -Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler, - courtesy of e000 (https://github.com/e000): https://gist.github.com/869791#file_socksipyhandler.py + courtesy of e000 (https://github.com/e000): + https://gist.github.com/869791#file_socksipyhandler.py -Re-styled code to make it readable -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc. -Improved exception handling and output - -Removed irritating use of sequence indexes, replaced with tuple unpacked variables + -Removed irritating use of sequence indexes, replaced with tuple unpacked + variables -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03" -Other general fixes --Added clarification that the HTTP proxy connection method only supports CONNECT-style tunneling HTTP proxies +-Added clarification that the HTTP proxy connection method only supports + CONNECT-style tunneling HTTP proxies -Various small bug fixes """ -__version__ = "1.6.7" - -import socket -import struct +from base64 import b64encode +from collections import Callable from errno import EOPNOTSUPP, EINVAL, EAGAIN +import functools from io import BytesIO -from os import SEEK_CUR +import logging import os +from os import SEEK_CUR +import socket +import struct import sys -import functools -import logging -from collections import Callable -from base64 import b64encode + +__version__ = "1.6.7" if os.name == "nt" and sys.version_info < (3, 0): try: import win_inet_pton except ImportError: - raise ImportError("To run PySocks on Windows you must install win_inet_pton") + raise ImportError( + "To run PySocks on Windows you must install win_inet_pton") log = logging.getLogger(__name__) @@ -90,22 +94,21 @@ def wrapper(*args, **kwargs): self = args[0] try: - _is_blocking = self.gettimeout() + _is_blocking = self.gettimeout() if _is_blocking == 0: self.setblocking(True) return function(*args, **kwargs) except Exception as e: raise finally: - # set orgin blcoking + # set orgin blocking if _is_blocking == 0: self.setblocking(False) return wrapper + class ProxyError(IOError): - """ - socket_err contains original socket.error exception. - """ + """Socket_err contains original socket.error exception.""" def __init__(self, msg, socket_err=None): self.msg = msg self.socket_err = socket_err @@ -116,64 +119,82 @@ def __str__(self): return self.msg -class GeneralProxyError(ProxyError): pass -class ProxyConnectionError(ProxyError): pass -class SOCKS5AuthError(ProxyError): pass -class SOCKS5Error(ProxyError): pass -class SOCKS4Error(ProxyError): pass -class HTTPError(ProxyError): pass - -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" - } - -DEFAULT_PORTS = { SOCKS4: 1080, - SOCKS5: 1080, - HTTP: 8080 - } -def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): - """ - set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]]) +class GeneralProxyError(ProxyError): + pass - Sets a default proxy which all further socksocket objects will use, - unless explicitly changed. All parameters are as for socket.set_proxy(). - """ + +class ProxyConnectionError(ProxyError): + pass + + +class SOCKS5AuthError(ProxyError): + pass + + +class SOCKS5Error(ProxyError): + pass + + +class SOCKS4Error(ProxyError): + pass + + +class HTTPError(ProxyError): + pass + +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" +} + +DEFAULT_PORTS = {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080} + + +def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, + username=None, password=None): + """Sets a default proxy. + + All further socksocket objects will use the default unless explicitly + changed. All parameters are as for socket.set_proxy().""" socksocket.default_proxy = (proxy_type, addr, port, rdns, username.encode() if username else None, password.encode() if password else None) + def setdefaultproxy(*args, **kwargs): - if 'proxytype' in kwargs: - kwargs['proxy_type'] = kwargs.pop('proxytype') + if "proxytype" in kwargs: + kwargs["proxy_type"] = kwargs.pop("proxytype") return set_default_proxy(*args, **kwargs) + def get_default_proxy(): - """ - Returns the default proxy, set by set_default_proxy. - """ + """Returns the default proxy, set by set_default_proxy.""" return socksocket.default_proxy getdefaultproxy = get_default_proxy + def wrap_module(module): - """ - Attempts to replace a module's socket library with a SOCKS socket. Must set - a default proxy using set_default_proxy(...) first. - This will only work on modules that import socket directly into the namespace; - most of the Python Standard Library falls into this category. - """ + """Attempts to replace a module's socket library with a SOCKS socket. + + Must set a default proxy using set_default_proxy(...) first. This will + only work on modules that import socket directly into the namespace; + most of the Python Standard Library falls into this category.""" if socksocket.default_proxy: module.socket.socket = socksocket else: @@ -181,10 +202,12 @@ wrapmodule = wrap_module -def create_connection(dest_pair, proxy_type=None, proxy_addr=None, + +def create_connection(dest_pair, + timeout=None, source_address=None, + proxy_type=None, proxy_addr=None, proxy_port=None, proxy_rdns=True, proxy_username=None, proxy_password=None, - timeout=None, source_address=None, socket_options=None): """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object @@ -199,10 +222,10 @@ """ # Remove IPv6 brackets on the remote address and proxy address. remote_host, remote_port = dest_pair - if remote_host.startswith('['): - remote_host = remote_host.strip('[]') - if proxy_addr and proxy_addr.startswith('['): - proxy_addr = proxy_addr.strip('[]') + if remote_host.startswith("["): + remote_host = remote_host.strip("[]") + if proxy_addr and proxy_addr.startswith("["): + proxy_addr = proxy_addr.strip("[]") err = None @@ -240,9 +263,9 @@ raise socket.error("gai returned empty list.") + class _BaseSocket(socket.socket): - """Allows Python 2's "delegated" methods such as send() to be overridden - """ + """Allows Python 2 delegated methods such as send() to be overridden.""" def __init__(self, *pos, **kw): _orig_socket.__init__(self, *pos, **kw) @@ -253,6 +276,7 @@ _savenames = list() + def _makemethod(name): return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw) for name in ("sendto", "send", "recvfrom", "recv"): @@ -266,6 +290,7 @@ _BaseSocket._savenames.append(name) setattr(_BaseSocket, name, _makemethod(name)) + class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object @@ -277,7 +302,8 @@ default_proxy = None - def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, *args, **kwargs): + def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, + proto=0, *args, **kwargs): if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM): msg = "Socket type must be stream or datagram, not {!r}" raise ValueError(msg.format(type)) @@ -295,10 +321,9 @@ self._timeout = None def _readall(self, file, count): - """ - Receive EXACTLY the number of bytes requested from the file object. - Blocks until the required number of bytes have been received. - """ + """Receive EXACTLY the number of bytes requested from the file object. + + Blocks until the required number of bytes have been received.""" data = b"" while len(data) < count: d = file.read(count - len(data)) @@ -325,39 +350,38 @@ else: self.settimeout(0.0) - def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): - """set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) - Sets the proxy to be used. + def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, + username=None, password=None): + """ Sets the proxy to be used. - proxy_type - The type of the proxy to be used. Three types + proxy_type - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS - servers and 8080 for HTTP proxy servers. + servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be performed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. - Only relevant when username is also provided. - """ + Only relevant when username is also provided.""" self.proxy = (proxy_type, addr, port, rdns, username.encode() if username else None, password.encode() if password else None) def setproxy(self, *args, **kwargs): - if 'proxytype' in kwargs: - kwargs['proxy_type'] = kwargs.pop('proxytype') + if "proxytype" in kwargs: + kwargs["proxy_type"] = kwargs.pop("proxytype") return self.set_proxy(*args, **kwargs) def bind(self, *pos, **kw): - """ - Implements proxy connection for UDP sockets, - which happens during the bind() phase. - """ - proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy + """Implements proxy connection for UDP sockets. + + Happens during the bind() phase.""" + (proxy_type, proxy_addr, proxy_port, rdns, username, + password) = self.proxy if not proxy_type or self.type != socket.SOCK_DGRAM: return _orig_socket.bind(self, *pos, **kw) @@ -405,7 +429,8 @@ header.write(STANDALONE) self._write_SOCKS5_address(address, header) - sent = super(socksocket, self).send(header.getvalue() + bytes, *flags, **kwargs) + sent = super(socksocket, self).send(header.getvalue() + bytes, *flags, + **kwargs) return sent - header.tell() def send(self, bytes, flags=0, **kwargs): @@ -444,9 +469,7 @@ return super(socksocket, self).close() def get_proxy_sockname(self): - """ - Returns the bound IP address and port number at the proxy. - """ + """Returns the bound IP address and port number at the proxy.""" return self.proxy_sockname getproxysockname = get_proxy_sockname @@ -455,26 +478,23 @@ """ Returns the IP and port number of the proxy. """ - return super(socksocket, self).getpeername() + return self.getpeername() getproxypeername = get_proxy_peername def get_peername(self): - """ - Returns the IP address and port number of the destination - machine (note: get_proxy_peername returns the proxy) - """ + """Returns the IP address and port number of the destination machine. + + Note: get_proxy_peername returns the proxy.""" return self.proxy_peername getpeername = get_peername def _negotiate_SOCKS5(self, *dest_addr): - """ - Negotiates a stream connection through a SOCKS5 server. - """ + """Negotiates a stream connection through a SOCKS5 server.""" CONNECT = b"\x01" - self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self, - CONNECT, dest_addr) + self.proxy_peername, self.proxy_sockname = self._SOCKS5_request( + self, CONNECT, dest_addr) def _SOCKS5_request(self, conn, cmd, dst): """ @@ -505,7 +525,8 @@ if chosen_auth[0:1] != b"\x05": # Note: string[i:i+1] is used because indexing of a bytestring # via bytestring[i] yields an integer in Python 3 - raise GeneralProxyError("SOCKS5 proxy server sent invalid data") + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") # Check the chosen authentication method @@ -520,7 +541,8 @@ auth_status = self._readall(reader, 2) if auth_status[0:1] != b"\x01": # Bad response - raise GeneralProxyError("SOCKS5 proxy server sent invalid data") + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") if auth_status[1:2] != b"\x00": # Authentication failed raise SOCKS5AuthError("SOCKS5 authentication failed") @@ -531,9 +553,12 @@ elif chosen_auth[1:2] != b"\x00": # Reaching here is always bad if chosen_auth[1:2] == b"\xFF": - raise SOCKS5AuthError("All offered SOCKS5 authentication methods were rejected") + raise SOCKS5AuthError( + "All offered SOCKS5 authentication methods were" + " rejected") else: - raise GeneralProxyError("SOCKS5 proxy server sent invalid data") + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") # Now we can request the actual connection writer.write(b"\x05" + cmd + b"\x00") @@ -543,7 +568,8 @@ # Get the response resp = self._readall(reader, 3) if resp[0:1] != b"\x05": - raise GeneralProxyError("SOCKS5 proxy server sent invalid data") + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") status = ord(resp[1:2]) if status != 0x00: @@ -585,11 +611,14 @@ # Well it's not an IP number, so it's probably a DNS name. if rdns: # Resolve remotely - host_bytes = host.encode('idna') + host_bytes = host.encode("idna") file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) else: # Resolve locally - addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG) + addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, + socket.SOCK_STREAM, + socket.IPPROTO_TCP, + socket.AI_ADDRCONFIG) # We can't really work out what IP is reachable, so just pick the # first. target_addr = addresses[0] @@ -618,9 +647,7 @@ return addr, port def _negotiate_SOCKS4(self, dest_addr, dest_port): - """ - Negotiates a connection through a SOCKS4 server. - """ + """Negotiates a connection through a SOCKS4 server.""" proxy_type, addr, port, rdns, username, password = self.proxy writer = self.makefile("wb") @@ -636,7 +663,8 @@ addr_bytes = b"\x00\x00\x00\x01" remote_resolve = True else: - addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr)) + addr_bytes = socket.inet_aton( + socket.gethostbyname(dest_addr)) # Construct the request packet writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port)) @@ -651,14 +679,15 @@ # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if remote_resolve: - writer.write(dest_addr.encode('idna') + b"\x00") + writer.write(dest_addr.encode("idna") + b"\x00") writer.flush() # Get the response from the server resp = self._readall(reader, 8) if resp[0:1] != b"\x00": # Bad data - raise GeneralProxyError("SOCKS4 proxy server sent invalid data") + raise GeneralProxyError( + "SOCKS4 proxy server sent invalid data") status = ord(resp[1:2]) if status != 0x5A: @@ -667,7 +696,8 @@ raise SOCKS4Error("{0:#04x}: {1}".format(status, error)) # Get the bound address/port - self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) + self.proxy_sockname = (socket.inet_ntoa(resp[4:]), + struct.unpack(">H", resp[2:4])[0]) if remote_resolve: self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port else: @@ -677,22 +707,23 @@ writer.close() def _negotiate_HTTP(self, dest_addr, dest_port): - """ - Negotiates a connection through an HTTP server. - NOTE: This currently only supports HTTP CONNECT-style proxies. - """ + """Negotiates a connection through an HTTP server. + + NOTE: This currently only supports HTTP CONNECT-style proxies.""" proxy_type, addr, port, rdns, username, password = self.proxy # If we need to resolve locally, we do this now addr = dest_addr if rdns else socket.gethostbyname(dest_addr) http_headers = [ - b"CONNECT " + addr.encode('idna') + b":" + str(dest_port).encode() + b" HTTP/1.1", - b"Host: " + dest_addr.encode('idna') + (b"CONNECT " + addr.encode("idna") + b":" + + str(dest_port).encode() + b" HTTP/1.1"), + b"Host: " + dest_addr.encode("idna") ] if username and password: - http_headers.append(b"Proxy-Authorization: basic " + b64encode(username + b":" + password)) + http_headers.append(b"Proxy-Authorization: basic " + + b64encode(username + b":" + password)) http_headers.append(b"\r\n") @@ -712,19 +743,23 @@ raise GeneralProxyError("HTTP proxy server sent invalid response") if not proto.startswith("HTTP/"): - raise GeneralProxyError("Proxy server does not appear to be an HTTP proxy") + raise GeneralProxyError( + "Proxy server does not appear to be an HTTP proxy") try: status_code = int(status_code) except ValueError: - raise HTTPError("HTTP proxy server did not return a valid HTTP status") + raise HTTPError( + "HTTP proxy server did not return a valid HTTP status") if status_code != 200: error = "{0}: {1}".format(status_code, status_msg) if status_code in (400, 403, 405): - # It's likely that the HTTP proxy server does not support the CONNECT tunneling method - error += ("\n[*] Note: The HTTP proxy server may not be supported by PySocks" - " (must be a CONNECT tunnel proxy)") + # It's likely that the HTTP proxy server does not support the + # CONNECT tunneling method + error += ("\n[*] Note: The HTTP proxy server may not be" + " supported by PySocks (must be a CONNECT tunnel" + " proxy)") raise HTTPError(error) self.proxy_sockname = (b"0.0.0.0", 0) @@ -749,7 +784,8 @@ # Probably IPv6, not supported -- raise an error, and hope # Happy Eyeballs (RFC6555) makes sure at least the IPv4 # connection works... - raise socket.error("PySocks doesn't support IPv6: %s" % str(dest_pair)) + raise socket.error("PySocks doesn't support IPv6: %s" + % str(dest_pair)) dest_addr, dest_port = dest_pair @@ -766,15 +802,17 @@ self.proxy_peername = (dest_addr, dest_port) return - proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy + (proxy_type, proxy_addr, proxy_port, rdns, username, + password) = self.proxy # Do a minimal input check first if (not isinstance(dest_pair, (list, tuple)) or len(dest_pair) != 2 or not dest_addr or not isinstance(dest_port, int)): - raise GeneralProxyError("Invalid destination-connection (host, port) pair") - + # Inputs failed, raise an error + raise GeneralProxyError( + "Invalid destination-connection (host, port) pair") # We set the timeout here so that we don't hang in connection or during # negotiation. @@ -801,7 +839,7 @@ printable_type = PRINTABLE_PROXY_TYPES[proxy_type] msg = "Error connecting to {0} proxy {1}".format(printable_type, - proxy_server) + proxy_server) log.debug("%s due to: %s", msg, error) raise ProxyConnectionError(msg, error) @@ -824,7 +862,8 @@ """ Return proxy address to connect to as tuple object """ - proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy + (proxy_type, proxy_addr, proxy_port, rdns, username, + password) = self.proxy proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) if not proxy_port: raise GeneralProxyError("Invalid proxy type")
