[Python-modules-commits] [python-socksipy] 05/10: Import python-socksipy_1.5.0+dfsg.orig.tar.gz

Wolfgang Borgert debacle at moszumanska.debian.org
Fri Jan 8 00:26:34 UTC 2016


This is an automated email from the git hooks/post-receive script.

debacle pushed a commit to branch master
in repository python-socksipy.

commit 68697041593a88e9ad2b70ab20dcf457461703ab
Author: W. Martin Borgert <debacle at debian.org>
Date:   Mon Dec 28 01:07:51 2015 +0100

    Import python-socksipy_1.5.0+dfsg.orig.tar.gz
---
 BUGS                 |  25 ---
 LICENSE              |  44 ++--
 PKG-INFO             |  10 -
 README               | 201 -----------------
 README.md            | 292 ++++++++++++++++++++++++
 setup.py             |  34 +--
 socks.py             | 613 ++++++++++++++++++++++++++++++---------------------
 sockshandler.py      |  39 ++++
 test/README          |   5 +
 test/httpproxy.py    | 137 ++++++++++++
 test/mocks.conf      | 104 +++++++++
 test/socks4server.py |  14 ++
 test/sockstest.py    | 174 +++++++++++++++
 test/test.sh         |  17 ++
 14 files changed, 1186 insertions(+), 523 deletions(-)

diff --git a/BUGS b/BUGS
deleted file mode 100644
index 2412351..0000000
--- a/BUGS
+++ /dev/null
@@ -1,25 +0,0 @@
-SocksiPy version 1.00
-A Python SOCKS module.
-(C) 2006 Dan-Haim. All rights reserved.
-See LICENSE file for details.
-
-
-KNOWN BUGS AND ISSUES
-----------------------
-
-There are no currently known bugs in this module.
-There are some limits though:
-
-1) Only outgoing connections are supported - This module currently only supports
-outgoing TCP connections, though some servers may support incoming connections
-as well. UDP is not supported either.
-
-2) GSSAPI Socks5 authenticaion is not supported.
-
-
-If you find any new bugs, please contact the author at:
-
-negativeiq at users.sourceforge.net
-
-
-Thank you!
diff --git a/LICENSE b/LICENSE
index fc33078..04b6b1f 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,22 +1,22 @@
-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:
-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,
-   this list of conditions and the following disclaimer in the documentation
-   and/or other materials provided with the distribution.
-3. Neither the name of Dan Haim nor the names of his contributors may be used
-   to endorse or promote products derived from this software without specific
-   prior written permission.
-   
-THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
-WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-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.
+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:
+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,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+3. Neither the name of Dan Haim nor the names of his contributors may be used
+   to endorse or promote products derived from this software without specific
+   prior written permission.
+   
+THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+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.
diff --git a/PKG-INFO b/PKG-INFO
deleted file mode 100644
index e24da45..0000000
--- a/PKG-INFO
+++ /dev/null
@@ -1,10 +0,0 @@
-Metadata-Version: 1.0
-Name: SocksiPy-branch
-Version: 1.02
-Summary: A Python SOCKS module
-Home-page: http://socksipy.sourceforge.net/
-Author: Dan-Haim
-Author-email: negativeiq at users.sourceforge.net
-License: BSD
-Description: This Python module allows you to create TCP connections through a SOCKS proxy without any special effort.
-Platform: UNKNOWN
diff --git a/README b/README
deleted file mode 100644
index deae6f6..0000000
--- a/README
+++ /dev/null
@@ -1,201 +0,0 @@
-SocksiPy version 1.00
-A Python SOCKS module.
-(C) 2006 Dan-Haim. All rights reserved.
-See LICENSE file for details.
-
-
-WHAT IS A SOCKS PROXY?
-A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as
-a tunnel, relaying all traffic going through it without modifying it.
-SOCKS proxies can be used to relay traffic using any network protocol that
-uses TCP.
-
-WHAT IS SOCKSIPY?
-This Python module allows you to create TCP connections through a SOCKS
-proxy without any special effort.
-
-PROXY COMPATIBILITY
-SocksiPy is compatible with three different types of proxies:
-1. SOCKS Version 4 (Socks4), including the Socks4a extension.
-2. SOCKS Version 5 (Socks5).
-3. HTTP Proxies which support tunneling using the CONNECT method.
-
-SYSTEM REQUIREMENTS
-Being written in Python, SocksiPy can run on any platform that has a Python
-interpreter and TCP/IP support.
-This module has been tested with Python 2.3 and should work with greater versions
-just as well.
-
-
-INSTALLATION
--------------
-
-Simply copy the file "socks.py" to your Python's lib/site-packages directory,
-and you're ready to go.
-
-
-USAGE
-------
-
-First load the socks module with the command:
-
->>> import socks
->>>
-
-The socks module provides a class called "socksocket", which is the base to
-all of the module's functionality.
-The socksocket object has the same initialization parameters as the normal socket
-object to ensure maximal compatibility, however it should be noted that socksocket
-will only function with family being AF_INET and type being SOCK_STREAM.
-Generally, it is best to initialize the socksocket object with no parameters
-
->>> s = socks.socksocket()
->>>
-
-The socksocket object has an interface which is very similiar to socket's (in fact
-the socksocket class is derived from socket) with a few extra methods.
-To select the proxy server you would like to use, use the setproxy method, whose
-syntax is:
-
-setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
-
-Explaination of the parameters:
-
-proxytype - The type of the proxy server. This can be one of three possible
-choices: PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP for Socks4,
-Socks5 and HTTP servers respectively.
-
-addr - The IP address or DNS name of the proxy server.
-
-port - The port of the proxy server. Defaults to 1080 for socks and 8080 for http.
-
-rdns - This is a boolean flag than modifies the behavior regarding DNS resolving.
-If it is set to True, DNS resolving will be preformed remotely, on the server.
-If it is set to False, DNS resolving will be preformed locally. Please note that
-setting this to True with Socks4 servers actually use an extension to the protocol,
-called Socks4a, which may not be supported on all servers (Socks5 and http servers
-always support DNS). The default is True.
-
-username - For Socks5 servers, this allows simple username / password authentication
-with the server. For Socks4 servers, this parameter will be sent as the userid.
-This parameter is ignored if an HTTP server is being used. If it is not provided,
-authentication will not be used (servers may accept unauthentication requests).
-
-password - This parameter is valid only for Socks5 servers and specifies the
-respective password for the username provided.
-
-Example of usage:
-
->>> s.setproxy(socks.PROXY_TYPE_SOCKS5,"socks.example.com")
->>>
-
-After the setproxy method has been called, simply call the connect method with the
-traditional parameters to establish a connection through the proxy:
-
->>> s.connect(("www.sourceforge.net",80))
->>>
-
-Connection will take a bit longer to allow negotiation with the proxy server.
-Please note that calling connect without calling setproxy earlier will connect
-without a proxy (just like a regular socket).
-
-Errors: Any errors in the connection process will trigger exceptions. The exception
-may either be generated by the underlying socket layer or may be custom module
-exceptions, whose details follow:
-
-class ProxyError - This is a base exception class. It is not raised directly but
-rather all other exception classes raised by this module are derived from it.
-This allows an easy way to catch all proxy-related errors.
-
-class GeneralProxyError - When thrown, it indicates a problem which does not fall
-into another category. The parameter is a tuple containing an error code and a
-description of the error, from the following list:
-1 - invalid data - This error means that unexpected data has been received from
-the server. The most common reason is that the server specified as the proxy is
-not really a Socks4/Socks5/HTTP proxy, or maybe the proxy type specified is wrong.
-4 - bad proxy type - This will be raised if the type of the proxy supplied to the
-setproxy function was not PROXY_TYPE_SOCKS4/PROXY_TYPE_SOCKS5/PROXY_TYPE_HTTP.
-5 - bad input - This will be raised if the connect method is called with bad input
-parameters.
-
-class Socks5AuthError - This indicates that the connection through a Socks5 server
-failed due to an authentication problem. The parameter is a tuple containing a
-code and a description message according to the following list:
-
-1 - authentication is required - This will happen if you use a Socks5 server which
-requires authentication without providing a username / password at all.
-2 - all offered authentication methods were rejected - This will happen if the proxy
-requires a special authentication method which is not supported by this module.
-3 - unknown username or invalid password - Self descriptive.
-
-class Socks5Error - This will be raised for Socks5 errors which are not related to
-authentication. The parameter is a tuple containing a code and a description of the
-error, as given by the server. The possible errors, according to the RFC are:
-
-1 - General SOCKS server failure - If for any reason the proxy server is unable to
-fulfill your request (internal server error).
-2 - connection not allowed by ruleset - If the address you're trying to connect to
-is blacklisted on the server or requires authentication.
-3 - Network unreachable - The target could not be contacted. A router on the network
-had replied with a destination net unreachable error.
-4 - Host unreachable - The target could not be contacted. A router on the network
-had replied with a destination host unreachable error.
-5 - Connection refused - The target server has actively refused the connection
-(the requested port is closed).
-6 - TTL expired - The TTL value of the SYN packet from the proxy to the target server
-has expired. This usually means that there are network problems causing the packet
-to be caught in a router-to-router "ping-pong".
-7 - Command not supported - The client has issued an invalid command. When using this
-module, this error should not occur.
-8 - Address type not supported - The client has provided an invalid address type.
-When using this module, this error should not occur.
-
-class Socks4Error - This will be raised for Socks4 errors. The parameter is a tuple
-containing a code and a description of the error, as given by the server. The
-possible error, according to the specification are:
-
-1 - Request rejected or failed - Will be raised in the event of an failure for any
-reason other then the two mentioned next.
-2 - request rejected because SOCKS server cannot connect to identd on the client -
-The Socks server had tried an ident lookup on your computer and has failed. In this
-case you should run an identd server and/or configure your firewall to allow incoming
-connections to local port 113 from the remote server.
-3 - request rejected because the client program and identd report different user-ids - 
-The Socks server had performed an ident lookup on your computer and has received a
-different userid than the one you have provided. Change your userid (through the
-username parameter of the setproxy method) to match and try again.
-
-class HTTPError - This will be raised for HTTP errors. The parameter is a tuple
-containing the HTTP status code and the description of the server.
-
-
-After establishing the connection, the object behaves like a standard socket.
-Call the close method to close the connection.
-
-In addition to the socksocket class, an additional function worth mentioning is the
-setdefaultproxy function. The parameters are the same as the setproxy method.
-This function will set default proxy settings for newly created socksocket objects,
-in which the proxy settings haven't been changed via the setproxy method.
-This is quite useful if you wish to force 3rd party modules to use a socks proxy,
-by overriding the socket object.
-For example:
-
->>> socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,"socks.example.com")
->>> socket.socket = socks.socksocket
->>> urllib.urlopen("http://www.sourceforge.net/")
-
-
-PROBLEMS
----------
-
-If you have any problems using this module, please first refer to the BUGS file
-(containing current bugs and issues). If your problem is not mentioned you may
-contact the author at the following E-Mail address:
-
-negativeiq at users.sourceforge.net
-
-Please allow some time for your question to be received and handled.
-
-
-Dan-Haim,
-Author.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ad8ce9f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,292 @@
+PySocks
+=======
+
+Updated version of SocksiPy. Many old bugs fixed, and overall code cleanup.
+
+**Version:** 1.5.0
+
+----------------
+
+Features
+========
+
+* Fully supports Python 2.6 - 3.4
+
+* SocksiPyHandler, courtesy e000, was also added as an example of how this module can be used with urllib2. See example code in sockshandler.py.
+
+* Bugs in the original SocksiPy were fixed, including two that could lead to infinite hanging when communicating with bad proxy servers.
+
+* urllib3, which powers the requests module, is working on integrating SOCKS proxy support based on this branch
+
+* `SOCKS5`, `SOCKS4`, and `HTTP` are now aliases for `PROXY_TYPE_SOCKS5`, `PROXY_TYPE_SOCKS4`, and `PROXY_TYPE_HTTP`
+
+* Tests added
+
+* Various style and performance improvements; codebase simplified
+
+* Actively maintained
+
+Installation
+============
+
+    pip install PySocks
+    
+Or download the tarball / `git clone` and...
+
+    python setup.py install
+    
+Alternatively, include just `socks.py` in your project.
+
+--------------------------------------------
+
+*Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP proxies (and not SOCKS proxies), it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead.
+
+--------------------------------------------
+
+Usage
+=====
+
+## Example ##
+
+    import socks
+    
+    s = socks.socksocket()
+    
+    s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default
+    # Or
+    s.set_proxy(socks.SOCKS4, "localhost", 4444)
+    # Or
+    s.set_proxy(socks.HTTP, "5.5.5.5", 8888)
+
+    # Can be treated identical to a regular socket object
+    s.connect(("www.test.com", 80))
+    s.sendall("GET / ...")
+    print s.recv(4096)
+
+
+To monkeypatch the entire standard library with a single default proxy:
+
+    import socket
+    import socks
+    import urllib2
+    
+    socks.set_default_proxy(socks.SOCKS5, "localhost")
+    socket.socket = socks.socksocket
+    
+    urllib2.urlopen("http://...") # All requests will pass through the SOCKS proxy
+    
+Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended.
+    
+--------------------------------------------
+    
+Original SocksiPy README attached below, amended to reflect API changes.
+
+--------------------------------------------
+
+SocksiPy - version 1.5.0
+
+A Python SOCKS module.
+
+(C) 2006 Dan-Haim. All rights reserved.
+
+See LICENSE file for details.
+
+
+*WHAT IS A SOCKS PROXY?*
+
+A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as
+a tunnel, relaying all traffic going through it without modifying it.
+SOCKS proxies can be used to relay traffic using any network protocol that
+uses TCP.
+
+*WHAT IS SOCKSIPY?*
+
+This Python module allows you to create TCP connections through a SOCKS
+proxy without any special effort.
+
+*PROXY COMPATIBILITY*
+
+SocksiPy is compatible with three different types of proxies:
+1. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension.
+2. SOCKS Version 5 (SOCKS5).
+3. HTTP Proxies which support tunneling using the CONNECT method.
+
+*SYSTEM REQUIREMENTS*
+
+Being written in Python, SocksiPy can run on any platform that has a Python
+interpreter and TCP/IP support.
+This module has been tested with Python 2.3 and should work with greater versions
+just as well.
+
+
+INSTALLATION
+-------------
+
+Simply copy the file "socks.py" to your Python's `lib/site-packages` directory,
+and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks]
+
+
+USAGE
+------
+
+First load the socks module with the command:
+
+    >>> import socks
+    >>>
+
+The socks module provides a class called `socksocket`, which is the base to
+all of the module's functionality.
+The `socksocket` object has the same initialization parameters as the normal socket
+object to ensure maximal compatibility, however it should be noted that `socksocket`
+will only function with family being `AF_INET` and type being `SOCK_STREAM`.
+Generally, it is best to initialize the `socksocket` object with no parameters
+
+    >>> s = socks.socksocket()
+    >>>
+
+The `socksocket` object has an interface which is very similiar to socket's (in fact
+the `socksocket` class is derived from socket) with a few extra methods.
+To select the proxy server you would like to use, use the `set_proxy` method, whose
+syntax is:
+
+    set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
+
+Explanation of the parameters:
+
+`proxy_type` - The type of the proxy server. This can be one of three possible
+choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4,
+SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively.
+
+`addr` - The IP address or DNS name of the proxy server.
+
+`port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http.
+
+`rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving.
+If it is set to True, DNS resolving will be preformed remotely, on the server.
+If it is set to False, DNS resolving will be preformed locally. Please note that
+setting this to True with SOCKS4 servers actually use an extension to the protocol,
+called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers
+always support DNS). The default is True.
+
+`username` - For SOCKS5 servers, this allows simple username / password authentication
+with the server. For SOCKS4 servers, this parameter will be sent as the userid.
+This parameter is ignored if an HTTP server is being used. If it is not provided,
+authentication will not be used (servers may accept unauthenticated requests).
+
+`password` - This parameter is valid only for SOCKS5 servers and specifies the
+respective password for the username provided.
+
+Example of usage:
+
+    >>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080
+    >>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081)
+
+After the set_proxy method has been called, simply call the connect method with the
+traditional parameters to establish a connection through the proxy:
+
+    >>> s.connect(("www.sourceforge.net", 80))
+    >>>
+
+Connection will take a bit longer to allow negotiation with the proxy server.
+Please note that calling connect without calling `set_proxy` earlier will connect
+without a proxy (just like a regular socket).
+
+Errors: Any errors in the connection process will trigger exceptions. The exception
+may either be generated by the underlying socket layer or may be custom module
+exceptions, whose details follow:
+
+class `ProxyError` - This is a base exception class. It is not raised directly but
+rather all other exception classes raised by this module are derived from it.
+This allows an easy way to catch all proxy-related errors. It descends from `IOError`.
+
+All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a
+caught `socket.error` exception, or `None` if there wasn't any.
+
+class `GeneralProxyError` - When thrown, it indicates a problem which does not fall
+into another category.
+
+* `Sent invalid data` - This error means that unexpected data has been received from
+the server. The most common reason is that the server specified as the proxy is
+not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong.
+
+* `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection.
+This may indicate that the proxy server is experiencing network or software problems.
+
+* `Bad proxy type` - This will be raised if the type of the proxy supplied to the
+set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`.
+
+* `Bad input` - This will be raised if the `connect()` method is called with bad input
+parameters.
+
+class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server
+failed due to an authentication problem.
+
+* `Authentication is required` - This will happen if you use a SOCKS5 server which
+requires authentication without providing a username / password at all.
+
+* `All offered authentication methods were rejected` - This will happen if the proxy
+requires a special authentication method which is not supported by this module.
+
+* `Unknown username or invalid password` - Self descriptive.
+
+class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to
+authentication. The parameter is a tuple containing a code and a description of the
+error, as given by the server. The possible errors, according to the RFC are:
+
+`0x01` - General SOCKS server failure - If for any reason the proxy server is unable to
+fulfill your request (internal server error).
+`0x02` - connection not allowed by ruleset - If the address you're trying to connect to
+is blacklisted on the server or requires authentication.
+`0x03` - Network unreachable - The target could not be contacted. A router on the network
+had replied with a destination net unreachable error.
+`0x04` - Host unreachable - The target could not be contacted. A router on the network
+had replied with a destination host unreachable error.
+`0x05` - Connection refused - The target server has actively refused the connection
+(the requested port is closed).
+`0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server
+has expired. This usually means that there are network problems causing the packet
+to be caught in a router-to-router "ping-pong".
+`0x07` - Command not supported - The client has issued an invalid command. When using this
+module, this error should not occur.
+`0x08` - Address type not supported - The client has provided an invalid address type.
+When using this module, this error should not occur.
+
+class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple
+containing a code and a description of the error, as given by the server. The
+possible error, according to the specification are:
+
+`0x5B` - Request rejected or failed - Will be raised in the event of an failure for any
+reason other then the two mentioned next.
+`0x5C` - request rejected because SOCKS server cannot connect to identd on the client -
+The Socks server had tried an ident lookup on your computer and has failed. In this
+case you should run an identd server and/or configure your firewall to allow incoming
+connections to local port 113 from the remote server.
+`0x5D` - request rejected because the client program and identd report different user-ids - 
+The Socks server had performed an ident lookup on your computer and has received a
+different userid than the one you have provided. Change your userid (through the
+username parameter of the set_proxy method) to match and try again.
+
+class `HTTPError` - This will be raised for HTTP errors. The message will contain
+the HTTP status code and provided error message.
+
+After establishing the connection, the object behaves like a standard socket.
+Methods like `makefile()` and `settimeout()` should behave just like regular sockets.
+Call the `close()` method to close the connection.
+
+In addition to the `socksocket` class, an additional function worth mentioning is the
+`set_default_proxy` function. The parameters are the same as the `set_proxy` method.
+This function will set default proxy settings for newly created `socksocket` objects,
+in which the proxy settings haven't been changed via the `set_proxy` method.
+This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy,
+by overriding the socket object.
+For example:
+
+    >>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com")
+    >>> socket.socket = socks.socksocket
+    >>> urllib.urlopen("http://www.sourceforge.net/")
+
+
+PROBLEMS
+---------
+
+Please open a GitHub issue at https://github.com/Anorov/PySocks
diff --git a/setup.py b/setup.py
old mode 100644
new mode 100755
index abc6867..068aef9
--- a/setup.py
+++ b/setup.py
@@ -1,17 +1,17 @@
-#!/usr/bin/env python
-from distutils.core import setup
-
-VERSION = "1.02"
-
-setup(
-name = "SocksiPy-branch",
-version = VERSION,
-description = "A Python SOCKS module",
-long_description = "This Python module allows you to create TCP connections through a SOCKS proxy without any special effort.",
-url = "http://socksipy.sourceforge.net/",
-author = "Dan-Haim",
-author_email="negativeiq at users.sourceforge.net",
-license = "BSD",
-py_modules=["socks"]
-)
-
+#!/usr/bin/env python
+from distutils.core import setup
+
+VERSION = "1.5.0"
+
+setup(
+    name = "PySocks",
+    version = VERSION,
+    description = "A Python SOCKS module",
+    url = "https://github.com/Anorov/PySocks",
+    download_url = "https://github.com/Anorov/PySocks/tarball/1.5.0",
+    license = "BSD",
+    author_email = "anorov.vorona at gmail.com",
+    keywords = ["socks", "proxy"],
+    py_modules=["socks"]
+)
+
diff --git a/socks.py b/socks.py
index 4e513fe..ca5ee1c 100644
--- a/socks.py
+++ b/socks.py
@@ -1,5 +1,6 @@
-"""SocksiPy - Python SOCKS module.
-Version 1.00
+"""
+SocksiPy - Python SOCKS module.
+Version 1.5.0
 
 Copyright 2006 Dan-Haim. All rights reserved.
 
@@ -28,9 +29,7 @@ OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
 This module provides a standard socket-like interface for Python
 for tunneling connections through SOCKS proxies.
 
-"""
-
-"""
+===============================================================================
 
 Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
 for use in PyLoris (http://pyloris.sourceforge.net/)
@@ -38,350 +37,468 @@ for use in PyLoris (http://pyloris.sourceforge.net/)
 Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
 mainly to merge bug fixes found in Sourceforge
 
+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)
+-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
+-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
+    -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
+-Various small bug fixes
 """
 
+__version__ = "1.5.0"
+
 import socket
 import struct
-import sys
 
-PROXY_TYPE_SOCKS4 = 1
-PROXY_TYPE_SOCKS5 = 2
-PROXY_TYPE_HTTP = 3
+PROXY_TYPE_SOCKS4 = SOCKS4 = 1
+PROXY_TYPE_SOCKS5 = SOCKS5 = 2
+PROXY_TYPE_HTTP = HTTP = 3
+
+PRINTABLE_PROXY_TYPES = {SOCKS4: "SOCKS4", SOCKS5: "SOCKS5", HTTP: "HTTP"}
+
+_orgsocket = _orig_socket = socket.socket
 
-_defaultproxy = None
-_orgsocket = socket.socket
+class ProxyError(IOError):
+    """
+    socket_err contains original socket.error exception.
+    """
+    def __init__(self, msg, socket_err=None):
+        self.msg = msg
+        self.socket_err = socket_err
+
+        if socket_err:
+            self.msg = msg + ": {}".format(socket_err)
+
+    def __str__(self):
+        return self.msg
 
-class ProxyError(Exception): pass
 class GeneralProxyError(ProxyError): pass
-class Socks5AuthError(ProxyError): pass
-class Socks5Error(ProxyError): pass
-class Socks4Error(ProxyError): pass
+class ProxyConnectionError(ProxyError): pass
+class SOCKS5AuthError(ProxyError): pass
+class SOCKS5Error(ProxyError): pass
+class SOCKS4Error(ProxyError): pass
 class HTTPError(ProxyError): pass
 
-_generalerrors = ("success",
-    "invalid data",
-    "not connected",
-    "not available",
-    "bad proxy type",
-    "bad input")
-
-_socks5errors = ("succeeded",
-    "general SOCKS server failure",
-    "connection not allowed by ruleset",
-    "Network unreachable",
-    "Host unreachable",
-    "Connection refused",
-    "TTL expired",
-    "Command not supported",
-    "Address type not supported",
-    "Unknown error")
-
-_socks5autherrors = ("succeeded",
-    "authentication is required",
-    "all offered authentication methods were rejected",
-    "unknown username or invalid password",
-    "unknown error")
-
-_socks4errors = ("request granted",
-    "request rejected or failed",
-    "request rejected because SOCKS server cannot connect to identd on the client",
-    "request rejected because the client program and identd report different user-ids",
-    "unknown error")
-
-def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
-    """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
+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]]])
+
     Sets a default proxy which all further socksocket objects will use,
     unless explicitly changed.
     """
-    global _defaultproxy
-    _defaultproxy = (proxytype, addr, port, rdns, username, password)
+    socksocket.default_proxy = (proxy_type, addr.encode(), port, rdns, 
+                                username.encode() if username else None,
+                                password.encode() if password else None)
+
+setdefaultproxy = set_default_proxy
+
+def get_default_proxy():
+    """
+    Returns the default proxy, set by set_default_proxy.
+    """
+    return socksocket.default_proxy
+
+getdefaultproxy = get_default_proxy
 
-def wrapmodule(module):
-    """wrapmodule(module)
+def wrap_module(module):
+    """
     Attempts to replace a module's socket library with a SOCKS socket. Must set
-    a default proxy using setdefaultproxy(...) first.
+    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 _defaultproxy != None:
+    if socksocket.default_proxy:
         module.socket.socket = socksocket
     else:
-        raise GeneralProxyError((4, "no proxy specified"))
+        raise GeneralProxyError("No default proxy specified")
+
+wrapmodule = wrap_module
+
+def create_connection(dest_pair, proxy_type=None, proxy_addr=None, 
+                      proxy_port=None, proxy_username=None,
+                      proxy_password=None, timeout=None):
+    """create_connection(dest_pair, **proxy_args) -> socket object
+
+    Like socket.create_connection(), but connects to proxy
+    before returning the socket object.
+
+    dest_pair - 2-tuple of (IP/hostname, port).
+    **proxy_args - Same args passed to socksocket.set_proxy().
+    timeout - Optional socket timeout value, in seconds.
+    """
+    sock = socksocket()
+    if isinstance(timeout, (int, float)):
+        sock.settimeout(timeout)
+    sock.set_proxy(proxy_type, proxy_addr, proxy_port,
+                   proxy_username, proxy_password)
+    sock.connect(dest_pair)
+    return sock
 
 class socksocket(socket.socket):
     """socksocket([family[, type[, proto]]]) -> socket object
+
     Open a SOCKS enabled socket. The parameters are the same as
     those of the standard socket init. In order for SOCKS to work,
     you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
     """
 
+    default_proxy = None
+
     def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
-        _orgsocket.__init__(self, family, type, proto, _sock)
-        if _defaultproxy != None:
-            self.__proxy = _defaultproxy
+        _orig_socket.__init__(self, family, type, proto, _sock)
+        
+        if self.default_proxy:
+            self.proxy = self.default_proxy
         else:
-            self.__proxy = (None, None, None, None, None, None)
-        self.__proxysockname = None
-        self.__proxypeername = None
+            self.proxy = (None, None, None, None, None, None)
+        self.proxy_sockname = None
+        self.proxy_peername = None
 
-    def __recvall(self, count):
-        """__recvall(count) -> data
+        self.proxy_negotiators = { SOCKS4: self._negotiate_SOCKS4,
+                                   SOCKS5: self._negotiate_SOCKS5,
+                                   HTTP: self._negotiate_HTTP
+                                 }
+
+    def _recvall(self, count):
+        """
         Receive EXACTLY the number of bytes requested from the socket.
         Blocks until the required number of bytes have been received.
         """
-        data = self.recv(count)
+        data = b""
         while len(data) < count:
-            d = self.recv(count-len(data))
-            if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
-            data = data + d
+            d = self.recv(count - len(data))
+            if not d:
+                raise GeneralProxyError("Connection closed unexpectedly")
+            data += d
         return data
 
-    def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
-        """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
+    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.
-        proxytype -    The type of the proxy to be used. Three types
-                are supported: PROXY_TYPE_SOCKS4 (including socks4a),
-                PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
+
+        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.
-        rdns -        Should DNS queries be preformed on the remote side
-                (rather than the local side). The default is True.
-                Note: This has no effect with SOCKS4 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.
+                       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.encode(), port, rdns, 
+                      username.encode() if username else None,
+                      password.encode() if password else None)
+
+    setproxy = set_proxy
+
+    def get_proxy_sockname(self):
+        """
+        Returns the bound IP address and port number at the proxy.
+        """
+        return self.proxy_sockname
+
+    getproxysockname = get_proxy_sockname
+
+    def get_proxy_peername(self):
         """
-        self.__proxy = (proxytype, addr, port, rdns, username, password)
+        Returns the IP and port number of the proxy.
+        """
+        return _orig_socket.getpeername(self)
+
+    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)
+        """
+        return self.proxy_peername
 
-    def __negotiatesocks5(self, destaddr, destport):
-        """__negotiatesocks5(self,destaddr,destport)
+    getpeername = get_peername
+
+    def _negotiate_SOCKS5(self, dest_addr, dest_port):
+        """
         Negotiates a connection through a SOCKS5 server.
         """
+        proxy_type, addr, port, rdns, username, password = self.proxy
+
         # First we'll send the authentication packages we support.
-        if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
+        if username and password:
             # The username/password details were supplied to the
-            # setproxy method so we support the USERNAME/PASSWORD
+            # set_proxy method so we support the USERNAME/PASSWORD
             # authentication (in addition to the standard none).
-            self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
+            self.sendall(b"\x05\x02\x00\x02")
         else:
             # No username/password were entered, therefore we
             # only support connections with no authentication.
-            self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
+            self.sendall(b"\x05\x01\x00")
+        
         # We'll receive the server's response to determine which
... 932 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-socksipy.git



More information about the Python-modules-commits mailing list