Browse Source

Update PySocks 1.6.5 (b4323df) → 1.6.8 (524ceb4).

pull/1080/head
JackDandy 7 years ago
parent
commit
9ce4e7c4d0
  1. 1
      CHANGES.md
  2. 340
      lib/socks/socks.py
  3. 1
      lib/win_inet_pton/__init__.py
  4. 84
      lib/win_inet_pton/win_inet_pton.py

1
CHANGES.md

@ -12,6 +12,7 @@
* Update moment.js 2.17.1 to 2.21.0 * Update moment.js 2.17.1 to 2.21.0
* Update profilehooks 1.9.0 (de7d59b) to 1.10.0 (0ce1e29) * Update profilehooks 1.9.0 (de7d59b) to 1.10.0 (0ce1e29)
* Update Certifi 2017.07.27 (f808089) to 2018.01.18 (e225253) * Update Certifi 2017.07.27 (f808089) to 2018.01.18 (e225253)
* Update PySocks 1.6.5 (b4323df) to 1.6.8 (524ceb4)
[develop changelog] [develop changelog]

340
lib/socks/socks.py

@ -1,11 +1,9 @@
""" """SocksiPy - Python SOCKS module.
SocksiPy - Python SOCKS module.
Version 1.6.5
Copyright 2006 Dan-Haim. All rights reserved. Copyright 2006 Dan-Haim. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, Redistribution and use in source and binary forms, with or without
are permitted provided that the following conditions are met: modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this 1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, 2. Redistributions in binary form must reproduce the above copyright notice,
@ -23,7 +21,7 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 This module provides a standard socket-like interface for Python
@ -39,37 +37,46 @@ mainly to merge bug fixes found in Sourceforge
Modifications made by Anorov (https://github.com/Anorov) Modifications made by Anorov (https://github.com/Anorov)
-Forked and renamed to PySocks -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, -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 -Re-styled code to make it readable
-Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc. -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc.
-Improved exception handling and output -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" -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03"
-Other general fixes -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 -Various small bug fixes
""" """
__version__ = "1.6.5" from base64 import b64encode
from collections import Callable
import socket
import struct
from errno import EOPNOTSUPP, EINVAL, EAGAIN from errno import EOPNOTSUPP, EINVAL, EAGAIN
import functools
from io import BytesIO from io import BytesIO
from os import SEEK_CUR import logging
import os import os
from os import SEEK_CUR
import socket
import struct
import sys import sys
from collections import Callable
from base64 import b64encode __version__ = "1.6.7"
if os.name == "nt" and sys.version_info < (3, 0): if os.name == "nt" and sys.version_info < (3, 0):
try: try:
import win_inet_pton import win_inet_pton
except ImportError: 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__)
PROXY_TYPE_SOCKS4 = SOCKS4 = 1 PROXY_TYPE_SOCKS4 = SOCKS4 = 1
PROXY_TYPE_SOCKS5 = SOCKS5 = 2 PROXY_TYPE_SOCKS5 = SOCKS5 = 2
@ -80,10 +87,28 @@ PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys()))
_orgsocket = _orig_socket = socket.socket _orgsocket = _orig_socket = socket.socket
def set_self_blocking(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
self = args[0]
try:
_is_blocking = self.gettimeout()
if _is_blocking == 0:
self.setblocking(True)
return function(*args, **kwargs)
except Exception as e:
raise
finally:
# set orgin blocking
if _is_blocking == 0:
self.setblocking(False)
return wrapper
class ProxyError(IOError): class ProxyError(IOError):
""" """Socket_err contains original socket.error exception."""
socket_err contains original socket.error exception.
"""
def __init__(self, msg, socket_err=None): def __init__(self, msg, socket_err=None):
self.msg = msg self.msg = msg
self.socket_err = socket_err self.socket_err = socket_err
@ -94,19 +119,40 @@ class ProxyError(IOError):
def __str__(self): def __str__(self):
return self.msg 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", class GeneralProxyError(ProxyError):
0x5C: "Request rejected because SOCKS server cannot connect to identd on the client", pass
0x5D: "Request rejected because the client program and identd report different user-ids"
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", SOCKS5_ERRORS = {
0x01: "General SOCKS server failure",
0x02: "Connection not allowed by ruleset", 0x02: "Connection not allowed by ruleset",
0x03: "Network unreachable", 0x03: "Network unreachable",
0x04: "Host unreachable", 0x04: "Host unreachable",
@ -116,39 +162,39 @@ SOCKS5_ERRORS = { 0x01: "General SOCKS server failure",
0x08: "Address type not supported" 0x08: "Address type not supported"
} }
DEFAULT_PORTS = { SOCKS4: 1080, DEFAULT_PORTS = {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080}
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]]])
Sets a default proxy which all further socksocket objects will use, def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True,
unless explicitly changed. All parameters are as for socket.set_proxy(). 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, socksocket.default_proxy = (proxy_type, addr, port, rdns,
username.encode() if username else None, username.encode() if username else None,
password.encode() if password else None) password.encode() if password else None)
setdefaultproxy = set_default_proxy
def setdefaultproxy(*args, **kwargs):
if "proxytype" in kwargs:
kwargs["proxy_type"] = kwargs.pop("proxytype")
return set_default_proxy(*args, **kwargs)
def get_default_proxy(): 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 return socksocket.default_proxy
getdefaultproxy = get_default_proxy getdefaultproxy = get_default_proxy
def wrap_module(module): def wrap_module(module):
""" """Attempts to replace a module's socket library with a SOCKS socket.
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using set_default_proxy(...) first. Must set a default proxy using set_default_proxy(...) first. This will
This will only work on modules that import socket directly into the namespace; only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category. most of the Python Standard Library falls into this category."""
"""
if socksocket.default_proxy: if socksocket.default_proxy:
module.socket.socket = socksocket module.socket.socket = socksocket
else: else:
@ -156,10 +202,12 @@ def wrap_module(module):
wrapmodule = wrap_module 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_port=None, proxy_rdns=True,
proxy_username=None, proxy_password=None, proxy_username=None, proxy_password=None,
timeout=None, source_address=None,
socket_options=None): socket_options=None):
"""create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
@ -174,10 +222,10 @@ def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
""" """
# Remove IPv6 brackets on the remote address and proxy address. # Remove IPv6 brackets on the remote address and proxy address.
remote_host, remote_port = dest_pair remote_host, remote_port = dest_pair
if remote_host.startswith('['): if remote_host.startswith("["):
remote_host = remote_host.strip('[]') remote_host = remote_host.strip("[]")
if proxy_addr and proxy_addr.startswith('['): if proxy_addr and proxy_addr.startswith("["):
proxy_addr = proxy_addr.strip('[]') proxy_addr = proxy_addr.strip("[]")
err = None err = None
@ -215,9 +263,9 @@ def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
raise socket.error("gai returned empty list.") raise socket.error("gai returned empty list.")
class _BaseSocket(socket.socket): 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): def __init__(self, *pos, **kw):
_orig_socket.__init__(self, *pos, **kw) _orig_socket.__init__(self, *pos, **kw)
@ -228,6 +276,7 @@ class _BaseSocket(socket.socket):
_savenames = list() _savenames = list()
def _makemethod(name): def _makemethod(name):
return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw) return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
for name in ("sendto", "send", "recvfrom", "recv"): for name in ("sendto", "send", "recvfrom", "recv"):
@ -241,6 +290,7 @@ for name in ("sendto", "send", "recvfrom", "recv"):
_BaseSocket._savenames.append(name) _BaseSocket._savenames.append(name)
setattr(_BaseSocket, name, _makemethod(name)) setattr(_BaseSocket, name, _makemethod(name))
class socksocket(_BaseSocket): class socksocket(_BaseSocket):
"""socksocket([family[, type[, proto]]]) -> socket object """socksocket([family[, type[, proto]]]) -> socket object
@ -252,12 +302,13 @@ class socksocket(_BaseSocket):
default_proxy = None 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): if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
msg = "Socket type must be stream or datagram, not {!r}" msg = "Socket type must be stream or datagram, not {!r}"
raise ValueError(msg.format(type)) raise ValueError(msg.format(type))
_BaseSocket.__init__(self, family, type, proto, *args, **kwargs) super(socksocket, self).__init__(family, type, proto, *args, **kwargs)
self._proxyconn = None # TCP connection to keep UDP relay alive self._proxyconn = None # TCP connection to keep UDP relay alive
if self.default_proxy: if self.default_proxy:
@ -270,10 +321,9 @@ class socksocket(_BaseSocket):
self._timeout = None self._timeout = None
def _readall(self, file, count): def _readall(self, file, count):
""" """Receive EXACTLY the number of bytes requested from the file object.
Receive EXACTLY the number of bytes requested from the file object.
Blocks until the required number of bytes have been received. Blocks until the required number of bytes have been received."""
"""
data = b"" data = b""
while len(data) < count: while len(data) < count:
d = file.read(count - len(data)) d = file.read(count - len(data))
@ -287,7 +337,7 @@ class socksocket(_BaseSocket):
try: try:
# test if we're connected, if so apply timeout # test if we're connected, if so apply timeout
peer = self.get_proxy_peername() peer = self.get_proxy_peername()
_BaseSocket.settimeout(self, self._timeout) super(socksocket, self).settimeout(self._timeout)
except socket.error: except socket.error:
pass pass
@ -300,9 +350,9 @@ class socksocket(_BaseSocket):
else: else:
self.settimeout(0.0) self.settimeout(0.0)
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True,
"""set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) username=None, password=None):
Sets the proxy to be used. """ 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), are supported: PROXY_TYPE_SOCKS4 (including socks4a),
@ -316,20 +366,22 @@ class socksocket(_BaseSocket):
username - Username to authenticate with to the server. username - Username to authenticate with to the server.
The default is no authentication. The default is no authentication.
password - Password to authenticate with to the server. 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, self.proxy = (proxy_type, addr, port, rdns,
username.encode() if username else None, username.encode() if username else None,
password.encode() if password else None) password.encode() if password else None)
setproxy = set_proxy def setproxy(self, *args, **kwargs):
if "proxytype" in kwargs:
kwargs["proxy_type"] = kwargs.pop("proxytype")
return self.set_proxy(*args, **kwargs)
def bind(self, *pos, **kw): def bind(self, *pos, **kw):
""" """Implements proxy connection for UDP sockets.
Implements proxy connection for UDP sockets,
which happens during the bind() phase. Happens during the bind() phase."""
""" (proxy_type, proxy_addr, proxy_port, rdns, username,
proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy password) = self.proxy
if not proxy_type or self.type != socket.SOCK_DGRAM: if not proxy_type or self.type != socket.SOCK_DGRAM:
return _orig_socket.bind(self, *pos, **kw) return _orig_socket.bind(self, *pos, **kw)
@ -338,7 +390,7 @@ class socksocket(_BaseSocket):
if proxy_type != SOCKS5: if proxy_type != SOCKS5:
msg = "UDP only supported by SOCKS5 proxy type" msg = "UDP only supported by SOCKS5 proxy type"
raise socket.error(EOPNOTSUPP, msg) raise socket.error(EOPNOTSUPP, msg)
_BaseSocket.bind(self, *pos, **kw) super(socksocket, self).bind(*pos, **kw)
# Need to specify actual local port because # Need to specify actual local port because
# some relays drop packets if a port of zero is specified. # some relays drop packets if a port of zero is specified.
@ -357,13 +409,13 @@ class socksocket(_BaseSocket):
# but some proxies return a private IP address (10.x.y.z) # but some proxies return a private IP address (10.x.y.z)
host, _ = proxy host, _ = proxy
_, port = relay _, port = relay
_BaseSocket.connect(self, (host, port)) super(socksocket, self).connect((host, port))
_BaseSocket.settimeout(self, self._timeout) super(socksocket, self).settimeout(self._timeout)
self.proxy_sockname = ("0.0.0.0", 0) # Unknown self.proxy_sockname = ("0.0.0.0", 0) # Unknown
def sendto(self, bytes, *args, **kwargs): def sendto(self, bytes, *args, **kwargs):
if self.type != socket.SOCK_DGRAM: if self.type != socket.SOCK_DGRAM:
return _BaseSocket.sendto(self, bytes, *args, **kwargs) return super(socksocket, self).sendto(bytes, *args, **kwargs)
if not self._proxyconn: if not self._proxyconn:
self.bind(("", 0)) self.bind(("", 0))
@ -377,22 +429,23 @@ class socksocket(_BaseSocket):
header.write(STANDALONE) header.write(STANDALONE)
self._write_SOCKS5_address(address, header) self._write_SOCKS5_address(address, header)
sent = _BaseSocket.send(self, header.getvalue() + bytes, *flags, **kwargs) sent = super(socksocket, self).send(header.getvalue() + bytes, *flags,
**kwargs)
return sent - header.tell() return sent - header.tell()
def send(self, bytes, flags=0, **kwargs): def send(self, bytes, flags=0, **kwargs):
if self.type == socket.SOCK_DGRAM: if self.type == socket.SOCK_DGRAM:
return self.sendto(bytes, flags, self.proxy_peername, **kwargs) return self.sendto(bytes, flags, self.proxy_peername, **kwargs)
else: else:
return _BaseSocket.send(self, bytes, flags, **kwargs) return super(socksocket, self).send(bytes, flags, **kwargs)
def recvfrom(self, bufsize, flags=0): def recvfrom(self, bufsize, flags=0):
if self.type != socket.SOCK_DGRAM: if self.type != socket.SOCK_DGRAM:
return _BaseSocket.recvfrom(self, bufsize, flags) return super(socksocket, self).recvfrom(bufsize, flags)
if not self._proxyconn: if not self._proxyconn:
self.bind(("", 0)) self.bind(("", 0))
buf = BytesIO(_BaseSocket.recv(self, bufsize + 1024, flags)) buf = BytesIO(super(socksocket, self).recv(bufsize + 1024, flags))
buf.seek(2, SEEK_CUR) buf.seek(2, SEEK_CUR)
frag = buf.read(1) frag = buf.read(1)
if ord(frag): if ord(frag):
@ -413,12 +466,10 @@ class socksocket(_BaseSocket):
def close(self): def close(self):
if self._proxyconn: if self._proxyconn:
self._proxyconn.close() self._proxyconn.close()
return _BaseSocket.close(self) return super(socksocket, self).close()
def get_proxy_sockname(self): 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 return self.proxy_sockname
getproxysockname = get_proxy_sockname getproxysockname = get_proxy_sockname
@ -427,26 +478,23 @@ class socksocket(_BaseSocket):
""" """
Returns the IP and port number of the proxy. Returns the IP and port number of the proxy.
""" """
return _BaseSocket.getpeername(self) return self.getpeername()
getproxypeername = get_proxy_peername getproxypeername = get_proxy_peername
def get_peername(self): def get_peername(self):
""" """Returns the IP address and port number of the destination machine.
Returns the IP address and port number of the destination
machine (note: get_proxy_peername returns the proxy) Note: get_proxy_peername returns the proxy."""
"""
return self.proxy_peername return self.proxy_peername
getpeername = get_peername getpeername = get_peername
def _negotiate_SOCKS5(self, *dest_addr): 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" CONNECT = b"\x01"
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self, self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
CONNECT, dest_addr) self, CONNECT, dest_addr)
def _SOCKS5_request(self, conn, cmd, dst): def _SOCKS5_request(self, conn, cmd, dst):
""" """
@ -477,7 +525,8 @@ class socksocket(_BaseSocket):
if chosen_auth[0:1] != b"\x05": if chosen_auth[0:1] != b"\x05":
# Note: string[i:i+1] is used because indexing of a bytestring # Note: string[i:i+1] is used because indexing of a bytestring
# via bytestring[i] yields an integer in Python 3 # 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 # Check the chosen authentication method
@ -492,7 +541,8 @@ class socksocket(_BaseSocket):
auth_status = self._readall(reader, 2) auth_status = self._readall(reader, 2)
if auth_status[0:1] != b"\x01": if auth_status[0:1] != b"\x01":
# Bad response # 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": if auth_status[1:2] != b"\x00":
# Authentication failed # Authentication failed
raise SOCKS5AuthError("SOCKS5 authentication failed") raise SOCKS5AuthError("SOCKS5 authentication failed")
@ -503,9 +553,12 @@ class socksocket(_BaseSocket):
elif chosen_auth[1:2] != b"\x00": elif chosen_auth[1:2] != b"\x00":
# Reaching here is always bad # Reaching here is always bad
if chosen_auth[1:2] == b"\xFF": 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: else:
raise GeneralProxyError("SOCKS5 proxy server sent invalid data") raise GeneralProxyError(
"SOCKS5 proxy server sent invalid data")
# Now we can request the actual connection # Now we can request the actual connection
writer.write(b"\x05" + cmd + b"\x00") writer.write(b"\x05" + cmd + b"\x00")
@ -515,7 +568,8 @@ class socksocket(_BaseSocket):
# Get the response # Get the response
resp = self._readall(reader, 3) resp = self._readall(reader, 3)
if resp[0:1] != b"\x05": 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]) status = ord(resp[1:2])
if status != 0x00: if status != 0x00:
@ -526,7 +580,7 @@ class socksocket(_BaseSocket):
# Get the bound address/port # Get the bound address/port
bnd = self._read_SOCKS5_address(reader) bnd = self._read_SOCKS5_address(reader)
_BaseSocket.settimeout(self, self._timeout) super(socksocket, self).settimeout(self._timeout)
return (resolved, bnd) return (resolved, bnd)
finally: finally:
reader.close() reader.close()
@ -557,11 +611,14 @@ class socksocket(_BaseSocket):
# Well it's not an IP number, so it's probably a DNS name. # Well it's not an IP number, so it's probably a DNS name.
if rdns: if rdns:
# Resolve remotely # Resolve remotely
host_bytes = host.encode('idna') host_bytes = host.encode("idna")
file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
else: else:
# Resolve locally # 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 # We can't really work out what IP is reachable, so just pick the
# first. # first.
target_addr = addresses[0] target_addr = addresses[0]
@ -590,9 +647,7 @@ class socksocket(_BaseSocket):
return addr, port return addr, port
def _negotiate_SOCKS4(self, dest_addr, dest_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 proxy_type, addr, port, rdns, username, password = self.proxy
writer = self.makefile("wb") writer = self.makefile("wb")
@ -608,7 +663,8 @@ class socksocket(_BaseSocket):
addr_bytes = b"\x00\x00\x00\x01" addr_bytes = b"\x00\x00\x00\x01"
remote_resolve = True remote_resolve = True
else: else:
addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr)) addr_bytes = socket.inet_aton(
socket.gethostbyname(dest_addr))
# Construct the request packet # Construct the request packet
writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port)) writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port))
@ -623,14 +679,15 @@ class socksocket(_BaseSocket):
# NOTE: This is actually an extension to the SOCKS4 protocol # NOTE: This is actually an extension to the SOCKS4 protocol
# called SOCKS4A and may not be supported in all cases. # called SOCKS4A and may not be supported in all cases.
if remote_resolve: if remote_resolve:
writer.write(dest_addr.encode('idna') + b"\x00") writer.write(dest_addr.encode("idna") + b"\x00")
writer.flush() writer.flush()
# Get the response from the server # Get the response from the server
resp = self._readall(reader, 8) resp = self._readall(reader, 8)
if resp[0:1] != b"\x00": if resp[0:1] != b"\x00":
# Bad data # Bad data
raise GeneralProxyError("SOCKS4 proxy server sent invalid data") raise GeneralProxyError(
"SOCKS4 proxy server sent invalid data")
status = ord(resp[1:2]) status = ord(resp[1:2])
if status != 0x5A: if status != 0x5A:
@ -639,7 +696,8 @@ class socksocket(_BaseSocket):
raise SOCKS4Error("{0:#04x}: {1}".format(status, error)) raise SOCKS4Error("{0:#04x}: {1}".format(status, error))
# Get the bound address/port # 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: if remote_resolve:
self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port
else: else:
@ -649,22 +707,23 @@ class socksocket(_BaseSocket):
writer.close() writer.close()
def _negotiate_HTTP(self, dest_addr, dest_port): def _negotiate_HTTP(self, dest_addr, dest_port):
""" """Negotiates a connection through an HTTP server.
Negotiates a connection through an HTTP server.
NOTE: This currently only supports HTTP CONNECT-style proxies. NOTE: This currently only supports HTTP CONNECT-style proxies."""
"""
proxy_type, addr, port, rdns, username, password = self.proxy proxy_type, addr, port, rdns, username, password = self.proxy
# If we need to resolve locally, we do this now # If we need to resolve locally, we do this now
addr = dest_addr if rdns else socket.gethostbyname(dest_addr) addr = dest_addr if rdns else socket.gethostbyname(dest_addr)
http_headers = [ http_headers = [
b"CONNECT " + addr.encode('idna') + b":" + str(dest_port).encode() + b" HTTP/1.1", (b"CONNECT " + addr.encode("idna") + b":"
b"Host: " + dest_addr.encode('idna') + str(dest_port).encode() + b" HTTP/1.1"),
b"Host: " + dest_addr.encode("idna")
] ]
if username and password: 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") http_headers.append(b"\r\n")
@ -684,19 +743,23 @@ class socksocket(_BaseSocket):
raise GeneralProxyError("HTTP proxy server sent invalid response") raise GeneralProxyError("HTTP proxy server sent invalid response")
if not proto.startswith("HTTP/"): 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: try:
status_code = int(status_code) status_code = int(status_code)
except ValueError: 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: if status_code != 200:
error = "{0}: {1}".format(status_code, status_msg) error = "{0}: {1}".format(status_code, status_msg)
if status_code in (400, 403, 405): if status_code in (400, 403, 405):
# It's likely that the HTTP proxy server does not support the CONNECT tunneling method # It's likely that the HTTP proxy server does not support the
error += ("\n[*] Note: The HTTP proxy server may not be supported by PySocks" # CONNECT tunneling method
" (must be a CONNECT tunnel proxy)") error += ("\n[*] Note: The HTTP proxy server may not be"
" supported by PySocks (must be a CONNECT tunnel"
" proxy)")
raise HTTPError(error) raise HTTPError(error)
self.proxy_sockname = (b"0.0.0.0", 0) self.proxy_sockname = (b"0.0.0.0", 0)
@ -708,7 +771,7 @@ class socksocket(_BaseSocket):
HTTP: _negotiate_HTTP HTTP: _negotiate_HTTP
} }
@set_self_blocking
def connect(self, dest_pair): def connect(self, dest_pair):
""" """
Connects to the specified destination through a proxy. Connects to the specified destination through a proxy.
@ -721,7 +784,8 @@ class socksocket(_BaseSocket):
# Probably IPv6, not supported -- raise an error, and hope # Probably IPv6, not supported -- raise an error, and hope
# Happy Eyeballs (RFC6555) makes sure at least the IPv4 # Happy Eyeballs (RFC6555) makes sure at least the IPv4
# connection works... # connection works...
raise socket.error("PySocks doesn't support IPv6") raise socket.error("PySocks doesn't support IPv6: %s"
% str(dest_pair))
dest_addr, dest_port = dest_pair dest_addr, dest_port = dest_pair
@ -738,32 +802,34 @@ class socksocket(_BaseSocket):
self.proxy_peername = (dest_addr, dest_port) self.proxy_peername = (dest_addr, dest_port)
return 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 # Do a minimal input check first
if (not isinstance(dest_pair, (list, tuple)) if (not isinstance(dest_pair, (list, tuple))
or len(dest_pair) != 2 or len(dest_pair) != 2
or not dest_addr or not dest_addr
or not isinstance(dest_port, int)): 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 # We set the timeout here so that we don't hang in connection or during
# negotiation. # negotiation.
_BaseSocket.settimeout(self, self._timeout) super(socksocket, self).settimeout(self._timeout)
if proxy_type is None: if proxy_type is None:
# Treat like regular socket object # Treat like regular socket object
self.proxy_peername = dest_pair self.proxy_peername = dest_pair
_BaseSocket.settimeout(self, self._timeout) super(socksocket, self).settimeout(self._timeout)
_BaseSocket.connect(self, (dest_addr, dest_port)) super(socksocket, self).connect((dest_addr, dest_port))
return return
proxy_addr = self._proxy_addr() proxy_addr = self._proxy_addr()
try: try:
# Initial connection to proxy server. # Initial connection to proxy server.
_BaseSocket.connect(self, proxy_addr) super(socksocket, self).connect(proxy_addr)
except socket.error as error: except socket.error as error:
# Error while connecting to proxy # Error while connecting to proxy
@ -774,6 +840,7 @@ class socksocket(_BaseSocket):
msg = "Error connecting to {0} proxy {1}".format(printable_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) raise ProxyConnectionError(msg, error)
else: else:
@ -795,7 +862,8 @@ class socksocket(_BaseSocket):
""" """
Return proxy address to connect to as tuple object 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) proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type)
if not proxy_port: if not proxy_port:
raise GeneralProxyError("Invalid proxy type") raise GeneralProxyError("Invalid proxy type")

1
lib/win_inet_pton/__init__.py

@ -0,0 +1 @@

84
lib/win_inet_pton/win_inet_pton.py

@ -0,0 +1,84 @@
# This software released into the public domain. Anyone is free to copy,
# modify, publish, use, compile, sell, or distribute this software,
# either in source code form or as a compiled binary, for any purpose,
# commercial or non-commercial, and by any means.
import socket
import ctypes
import os
class sockaddr(ctypes.Structure):
_fields_ = [("sa_family", ctypes.c_short),
("__pad1", ctypes.c_ushort),
("ipv4_addr", ctypes.c_byte * 4),
("ipv6_addr", ctypes.c_byte * 16),
("__pad2", ctypes.c_ulong)]
if hasattr(ctypes, 'windll'):
WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA
WSAAddressToStringA = ctypes.windll.ws2_32.WSAAddressToStringA
else:
def not_windows():
raise SystemError(
"Invalid platform. ctypes.windll must be available."
)
WSAStringToAddressA = not_windows
WSAAddressToStringA = not_windows
def inet_pton(address_family, ip_string):
addr = sockaddr()
addr.sa_family = address_family
addr_size = ctypes.c_int(ctypes.sizeof(addr))
if WSAStringToAddressA(
ip_string,
address_family,
None,
ctypes.byref(addr),
ctypes.byref(addr_size)
) != 0:
raise socket.error(ctypes.FormatError())
if address_family == socket.AF_INET:
return ctypes.string_at(addr.ipv4_addr, 4)
if address_family == socket.AF_INET6:
return ctypes.string_at(addr.ipv6_addr, 16)
raise socket.error('unknown address family')
def inet_ntop(address_family, packed_ip):
addr = sockaddr()
addr.sa_family = address_family
addr_size = ctypes.c_int(ctypes.sizeof(addr))
ip_string = ctypes.create_string_buffer(128)
ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string))
if address_family == socket.AF_INET:
if len(packed_ip) != ctypes.sizeof(addr.ipv4_addr):
raise socket.error('packed IP wrong length for inet_ntoa')
ctypes.memmove(addr.ipv4_addr, packed_ip, 4)
elif address_family == socket.AF_INET6:
if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr):
raise socket.error('packed IP wrong length for inet_ntoa')
ctypes.memmove(addr.ipv6_addr, packed_ip, 16)
else:
raise socket.error('unknown address family')
if WSAAddressToStringA(
ctypes.byref(addr),
addr_size,
None,
ip_string,
ctypes.byref(ip_string_size)
) != 0:
raise socket.error(ctypes.FormatError())
return ip_string[:ip_string_size.value - 1]
# Adding our two functions to the socket library
if os.name == 'nt':
socket.inet_pton = inet_pton
socket.inet_ntop = inet_ntop
Loading…
Cancel
Save