Commit f83e3826 authored by Martin's avatar Martin

Import PySocks 1.6.8 w/o 3proxy binary

parent 1db043b2
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
setup.cfg
Metadata-Version: 1.1
Name: PySocks
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
Author-email: anorov.vorona@gmail.com
License: BSD
Description: UNKNOWN
Keywords: socks,proxy
Platform: UNKNOWN
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Metadata-Version: 1.1
Name: PySocks
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
Author-email: anorov.vorona@gmail.com
License: BSD
Description: UNKNOWN
Keywords: socks,proxy
Platform: UNKNOWN
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
LICENSE
MANIFEST.in
README.md
setup.py
socks.py
sockshandler.py
PySocks.egg-info/PKG-INFO
PySocks.egg-info/SOURCES.txt
PySocks.egg-info/dependency_links.txt
PySocks.egg-info/top_level.txt
test/__init__.py
test/test_pysocks.py
test/util.py
test/bin/3proxy
test/bin/3proxy.license
\ No newline at end of file
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.
----------------
......
[egg_info]
tag_date = 0
tag_build =
tag_svn_revision = 0
#!/usr/bin/env python
from distutils.core import setup
import os
import sys
from setuptools import setup
VERSION = "1.6.5"
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,6 +19,11 @@ setup(
author = "Anorov",
author_email = "anorov.vorona@gmail.com",
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',
)
)
This diff is collapsed.
Very rudimentary tests for Python 2 and Python 3.
Requirements: tornado, twisted (available through pip)
./test.sh
#!/usr/bin/env python
#
# Simple asynchronous HTTP proxy with tunnelling (CONNECT).
#
# GET/POST proxying based on
# http://groups.google.com/group/python-tornado/msg/7bea08e7a049cf26
#
# Copyright (C) 2012 Senko Rasic <senko.rasic@dobarkod.hr>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys
import socket
import tornado.httpserver
import tornado.ioloop
import tornado.iostream
import tornado.web
import tornado.httpclient
__all__ = ['ProxyHandler', 'run_proxy']
class ProxyHandler(tornado.web.RequestHandler):
SUPPORTED_METHODS = ['GET', 'POST', 'CONNECT']
@tornado.web.asynchronous
def get(self):
def handle_response(response):
if response.error and not isinstance(response.error,
tornado.httpclient.HTTPError):
self.set_status(500)
self.write('Internal server error:\n' + str(response.error))
self.finish()
else:
self.set_status(response.code)
for header in ('Date', 'Cache-Control', 'Server',
'Content-Type', 'Location'):
v = response.headers.get(header)
if v:
self.set_header(header, v)
if response.body:
self.write(response.body)
self.finish()
req = tornado.httpclient.HTTPRequest(url=self.request.uri,
method=self.request.method, body=self.request.body,
headers=self.request.headers, follow_redirects=False,
allow_nonstandard_methods=True)
client = tornado.httpclient.AsyncHTTPClient()
try:
client.fetch(req, handle_response)
except tornado.httpclient.HTTPError as e:
if hasattr(e, 'response') and e.response:
self.handle_response(e.response)
else:
self.set_status(500)
self.write('Internal server error:\n' + str(e))
self.finish()
@tornado.web.asynchronous
def post(self):
return self.get()
@tornado.web.asynchronous
def connect(self):
host, port = self.request.uri.split(':')
client = self.request.connection.stream
def read_from_client(data):
upstream.write(data)
def read_from_upstream(data):
client.write(data)
def client_close(data=None):
if upstream.closed():
return
if data:
upstream.write(data)
upstream.close()
def upstream_close(data=None):
if client.closed():
return
if data:
client.write(data)
client.close()
def start_tunnel():
client.read_until_close(client_close, read_from_client)
upstream.read_until_close(upstream_close, read_from_upstream)
client.write(b'HTTP/1.0 200 Connection established\r\n\r\n')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
upstream = tornado.iostream.IOStream(s)
upstream.connect((host, int(port)), start_tunnel)
def run_proxy(port=8080, start_ioloop=True):
"""
Run proxy on the specified port. If start_ioloop is True (default),
the tornado IOLoop will be started immediately.
"""
app = tornado.web.Application([
(r'.*', ProxyHandler),
])
app.listen(port, address="127.0.0.1")
ioloop = tornado.ioloop.IOLoop.instance()
if start_ioloop:
ioloop.start()
if __name__ == '__main__':
port = 8081
if len(sys.argv) > 1:
port = int(sys.argv[1])
print ("Running HTTP proxy server")
run_proxy(port)
#!/usr/bin/env python
from twisted.internet import reactor
from twisted.protocols.socks import SOCKSv4Factory
def run_proxy():
reactor.listenTCP(1080, SOCKSv4Factory("/dev/null"), interface="127.0.0.1")
try:
reactor.run()
except (KeyboardInterrupt, SystemExit):
reactor.stop()
if __name__ == "__main__":
print("Running SOCKS4 proxy server")
run_proxy()
import sys
sys.path.append("..")
import socks
import socket
PY3K = sys.version_info[0] == 3
if PY3K:
import urllib.request as urllib2
else:
import sockshandler
import urllib2
def raw_HTTP_request():
req = "GET /ip HTTP/1.1\r\n"
req += "Host: ifconfig.me\r\n"
req += "User-Agent: Mozilla\r\n"
req += "Accept: text/html\r\n"
req += "\r\n"
return req.encode()
def socket_HTTP_test():
s = socks.socksocket()
s.set_proxy(socks.HTTP, "127.0.0.1", 8081)
s.connect(("ifconfig.me", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def socket_SOCKS4_test():
s = socks.socksocket()
s.set_proxy(socks.SOCKS4, "127.0.0.1", 1080)
s.connect(("ifconfig.me", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def socket_SOCKS5_test():
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081)
s.connect(("ifconfig.me", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def SOCKS5_connect_timeout_test():
s = socks.socksocket()
s.settimeout(0.0001)
s.set_proxy(socks.SOCKS5, "8.8.8.8", 80)
try:
s.connect(("ifconfig.me", 80))
except socks.ProxyConnectionError as e:
assert str(e.socket_err) == "timed out"
def SOCKS5_timeout_test():
s = socks.socksocket()
s.settimeout(0.0001)
s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081)
try:
s.connect(("ifconfig.me", 4444))
except socks.GeneralProxyError as e:
assert str(e.socket_err) == "timed out"
def socket_SOCKS5_auth_test():
# TODO: add support for this test. Will need a better SOCKS5 server.
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081, username="a", password="b")
s.connect(("ifconfig.me", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def socket_HTTP_IP_test():
s = socks.socksocket()
s.set_proxy(socks.HTTP, "127.0.0.1", 8081)
s.connect(("133.242.129.236", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def socket_SOCKS4_IP_test():
s = socks.socksocket()
s.set_proxy(socks.SOCKS4, "127.0.0.1", 1080)
s.connect(("133.242.129.236", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def socket_SOCKS5_IP_test():
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081)
s.connect(("133.242.129.236", 80))
s.sendall(raw_HTTP_request())
status = s.recv(2048).splitlines()[0]
assert status.startswith(b"HTTP/1.1 200")
def urllib2_HTTP_test():
socks.set_default_proxy(socks.HTTP, "127.0.0.1", 8081)
socks.wrap_module(urllib2)
status = urllib2.urlopen("http://ifconfig.me/ip").getcode()
assert status == 200
def urllib2_SOCKS5_test():
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 1081)
socks.wrap_module(urllib2)
status = urllib2.urlopen("http://ifconfig.me/ip").getcode()
assert status == 200
def urllib2_handler_HTTP_test():
opener = urllib2.build_opener(sockshandler.SocksiPyHandler(socks.HTTP, "127.0.0.1", 8081))
status = opener.open("http://ifconfig.me/ip").getcode()
assert status == 200
def urllib2_handler_SOCKS5_test():
opener = urllib2.build_opener(sockshandler.SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 1081))
status = opener.open("http://ifconfig.me/ip").getcode()
assert status == 200
def global_override_HTTP_test():
socks.set_default_proxy(socks.HTTP, "127.0.0.1", 8081)
good = socket.socket
socket.socket = socks.socksocket
status = urllib2.urlopen("http://ifconfig.me/ip").getcode()
socket.socket = good
assert status == 200
def global_override_SOCKS5_test():
default_proxy = (socks.SOCKS5, "127.0.0.1", 1081)
socks.set_default_proxy(*default_proxy)
good = socket.socket
socket.socket = socks.socksocket
status = urllib2.urlopen("http://ifconfig.me/ip").getcode()
socket.socket = good
assert status == 200
assert socks.get_default_proxy()[1].decode() == default_proxy[1]
def bail_early_with_ipv6_test():
sock = socks.socksocket()
ipv6_tuple = addr, port, flowinfo, scopeid = "::1", 1234, 0, 0
try:
sock.connect(ipv6_tuple)
except socket.error:
return
else:
assert False, "was expecting"
def main():
print("Running tests...")
socket_HTTP_test()
print("1/13")
socket_SOCKS4_test()
print("2/13")
socket_SOCKS5_test()
print("3/13")
if not PY3K:
urllib2_handler_HTTP_test()
print("3.33/13")
urllib2_handler_SOCKS5_test()
print("3.66/13")
socket_HTTP_IP_test()
print("4/13")
socket_SOCKS4_IP_test()
print("5/13")
socket_SOCKS5_IP_test()
print("6/13")
SOCKS5_connect_timeout_test()
print("7/13")
SOCKS5_timeout_test()
print("8/13")
urllib2_HTTP_test()
print("9/13")
urllib2_SOCKS5_test()
print("10/13")
global_override_HTTP_test()
print("11/13")
global_override_SOCKS5_test()
print("12/13")
bail_early_with_ipv6_test()
print("13/13")
print("All tests ran successfully")
if __name__ == "__main__":
main()
#!/bin/bash
shopt -s expand_aliases
type python2 >/dev/null 2>&1 || alias python2='python'
echo "Starting proxy servers..."
python2 socks4server.py > /dev/null &
python2 httpproxy.py > /dev/null &
echo "Ensure a SOCKS5 server is listening"
sleep 2
echo "Python 2.6 tests"
python2.6 sockstest.py
exit
sleep 2
echo "Python 2.7 tests"
python2.7 sockstest.py
sleep 2
echo "Python 3.x tests"
python3 sockstest.py
pkill python2 > /dev/null
./mocks shutdown
echo "Finished tests"
This diff is collapsed.
import time
from socket import socket, error, AF_INET, SOCK_STREAM
def wait_for_socket(server_name, host, port, timeout=2):
ok = False
for x in range(10):
try:
print('Testing [%s] proxy server on %s:%d'
% (server_name, host, port))
s = socket(AF_INET, SOCK_STREAM)
s.connect((host, port))
s.close()
except error as ex:
print('ERROR', ex)
time.sleep(timeout/10.0)
else:
print('Connection established')
ok = True
break
if not ok:
raise Exception('The %s proxy server has not started in %d seconds'
% (server_name, timeout))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment