We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Differentiate socks5h from socks5 and socks4a from socks4 when handling proxy string
In a proxy string, socks5h:// and socks4a:// mean that the hostname is
resolved by the SOCKS server.  socks5:// and socks4:// mean that the
hostname is resolved locally.  socks4a:// means to use SOCKS4a, which is
an extension of SOCKS4.  Let's make urllib3 honor it.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `dummyserver/testcase.py`
Content:
```
1 import unittest
2 import socket
3 import threading
4 from nose.plugins.skip import SkipTest
5 from tornado import ioloop, web
6 
7 from dummyserver.server import (
8     SocketServerThread,
9     run_tornado_app,
10     run_loop_in_thread,
11     DEFAULT_CERTS,
12 )
13 from dummyserver.handlers import TestingApp
14 from dummyserver.proxy import ProxyHandler
15 
16 
17 def consume_socket(sock, chunks=65536):
18     while not sock.recv(chunks).endswith(b'\r\n\r\n'):
19         pass
20 
21 
22 class SocketDummyServerTestCase(unittest.TestCase):
23     """
24     A simple socket-based server is created for this class that is good for
25     exactly one request.
26     """
27     scheme = 'http'
28     host = 'localhost'
29 
30     @classmethod
31     def _start_server(cls, socket_handler):
32         ready_event = threading.Event()
33         cls.server_thread = SocketServerThread(socket_handler=socket_handler,
34                                                ready_event=ready_event,
35                                                host=cls.host)
36         cls.server_thread.start()
37         ready_event.wait(5)
38         if not ready_event.is_set():
39             raise Exception("most likely failed to start server")
40         cls.port = cls.server_thread.port
41 
42     @classmethod
43     def start_response_handler(cls, response, num=1, block_send=None):
44         ready_event = threading.Event()
45 
46         def socket_handler(listener):
47             for _ in range(num):
48                 ready_event.set()
49 
50                 sock = listener.accept()[0]
51                 consume_socket(sock)
52                 if block_send:
53                     block_send.wait()
54                     block_send.clear()
55                 sock.send(response)
56                 sock.close()
57 
58         cls._start_server(socket_handler)
59         return ready_event
60 
61     @classmethod
62     def start_basic_handler(cls, **kw):
63         return cls.start_response_handler(
64             b'HTTP/1.1 200 OK\r\n'
65             b'Content-Length: 0\r\n'
66             b'\r\n', **kw)
67 
68     @classmethod
69     def tearDownClass(cls):
70         if hasattr(cls, 'server_thread'):
71             cls.server_thread.join(0.1)
72 
73 
74 class IPV4SocketDummyServerTestCase(SocketDummyServerTestCase):
75     @classmethod
76     def _start_server(cls, socket_handler):
77         ready_event = threading.Event()
78         cls.server_thread = SocketServerThread(socket_handler=socket_handler,
79                                                ready_event=ready_event,
80                                                host=cls.host)
81         cls.server_thread.USE_IPV6 = False
82         cls.server_thread.start()
83         ready_event.wait(5)
84         if not ready_event.is_set():
85             raise Exception("most likely failed to start server")
86         cls.port = cls.server_thread.port
87 
88 
89 class HTTPDummyServerTestCase(unittest.TestCase):
90     """ A simple HTTP server that runs when your test class runs
91 
92     Have your unittest class inherit from this one, and then a simple server
93     will start when your tests run, and automatically shut down when they
94     complete. For examples of what test requests you can send to the server,
95     see the TestingApp in dummyserver/handlers.py.
96     """
97     scheme = 'http'
98     host = 'localhost'
99     host_alt = '127.0.0.1'  # Some tests need two hosts
100     certs = DEFAULT_CERTS
101 
102     @classmethod
103     def _start_server(cls):
104         cls.io_loop = ioloop.IOLoop()
105         app = web.Application([(r".*", TestingApp)])
106         cls.server, cls.port = run_tornado_app(app, cls.io_loop, cls.certs,
107                                                cls.scheme, cls.host)
108         cls.server_thread = run_loop_in_thread(cls.io_loop)
109 
110     @classmethod
111     def _stop_server(cls):
112         cls.io_loop.add_callback(cls.server.stop)
113         cls.io_loop.add_callback(cls.io_loop.stop)
114         cls.server_thread.join()
115 
116     @classmethod
117     def setUpClass(cls):
118         cls._start_server()
119 
120     @classmethod
121     def tearDownClass(cls):
122         cls._stop_server()
123 
124 
125 class HTTPSDummyServerTestCase(HTTPDummyServerTestCase):
126     scheme = 'https'
127     host = 'localhost'
128     certs = DEFAULT_CERTS
129 
130 
131 class IPV6HTTPSDummyServerTestCase(HTTPSDummyServerTestCase):
132     host = '::1'
133 
134     @classmethod
135     def setUpClass(cls):
136         if not socket.has_ipv6:
137             raise SkipTest('IPv6 not available')
138         else:
139             super(IPV6HTTPSDummyServerTestCase, cls).setUpClass()
140 
141 
142 class HTTPDummyProxyTestCase(unittest.TestCase):
143 
144     http_host = 'localhost'
145     http_host_alt = '127.0.0.1'
146 
147     https_host = 'localhost'
148     https_host_alt = '127.0.0.1'
149     https_certs = DEFAULT_CERTS
150 
151     proxy_host = 'localhost'
152     proxy_host_alt = '127.0.0.1'
153 
154     @classmethod
155     def setUpClass(cls):
156         cls.io_loop = ioloop.IOLoop()
157 
158         app = web.Application([(r'.*', TestingApp)])
159         cls.http_server, cls.http_port = run_tornado_app(
160             app, cls.io_loop, None, 'http', cls.http_host)
161 
162         app = web.Application([(r'.*', TestingApp)])
163         cls.https_server, cls.https_port = run_tornado_app(
164             app, cls.io_loop, cls.https_certs, 'https', cls.http_host)
165 
166         app = web.Application([(r'.*', ProxyHandler)])
167         cls.proxy_server, cls.proxy_port = run_tornado_app(
168             app, cls.io_loop, None, 'http', cls.proxy_host)
169 
170         cls.server_thread = run_loop_in_thread(cls.io_loop)
171 
172     @classmethod
173     def tearDownClass(cls):
174         cls.io_loop.add_callback(cls.http_server.stop)
175         cls.io_loop.add_callback(cls.https_server.stop)
176         cls.io_loop.add_callback(cls.proxy_server.stop)
177         cls.io_loop.add_callback(cls.io_loop.stop)
178         cls.server_thread.join()
179 
180 
181 class IPv6HTTPDummyServerTestCase(HTTPDummyServerTestCase):
182     host = '::1'
183 
184     @classmethod
185     def setUpClass(cls):
186         if not socket.has_ipv6:
187             raise SkipTest('IPv6 not available')
188         else:
189             super(IPv6HTTPDummyServerTestCase, cls).setUpClass()
190 
191 
192 class IPv6HTTPDummyProxyTestCase(HTTPDummyProxyTestCase):
193 
194     http_host = 'localhost'
195     http_host_alt = '127.0.0.1'
196 
197     https_host = 'localhost'
198     https_host_alt = '127.0.0.1'
199     https_certs = DEFAULT_CERTS
200 
201     proxy_host = '::1'
202     proxy_host_alt = '127.0.0.1'
203
```

Path: `urllib3/contrib/socks.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """
3 This module contains provisional support for SOCKS proxies from within
4 urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and
5 SOCKS5. To enable its functionality, either install PySocks or install this
6 module with the ``socks`` extra.
7 
8 The SOCKS implementation supports the full range of urllib3 features. It also
9 supports the following SOCKS features:
10 
11 - SOCKS4
12 - SOCKS4a
13 - SOCKS5
14 - Usernames and passwords for the SOCKS proxy
15 
16 Known Limitations:
17 
18 - Currently PySocks does not support contacting remote websites via literal
19   IPv6 addresses. Any such connection attempt will fail. You must use a domain
20   name.
21 - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any
22   such connection attempt will fail.
23 """
24 from __future__ import absolute_import
25 
26 try:
27     import socks
28 except ImportError:
29     import warnings
30     from ..exceptions import DependencyWarning
31 
32     warnings.warn((
33         'SOCKS support in urllib3 requires the installation of optional '
34         'dependencies: specifically, PySocks.  For more information, see '
35         'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies'
36         ),
37         DependencyWarning
38     )
39     raise
40 
41 from socket import error as SocketError, timeout as SocketTimeout
42 
43 from ..connection import (
44     HTTPConnection, HTTPSConnection
45 )
46 from ..connectionpool import (
47     HTTPConnectionPool, HTTPSConnectionPool
48 )
49 from ..exceptions import ConnectTimeoutError, NewConnectionError
50 from ..poolmanager import PoolManager
51 from ..util.url import parse_url
52 
53 try:
54     import ssl
55 except ImportError:
56     ssl = None
57 
58 
59 class SOCKSConnection(HTTPConnection):
60     """
61     A plain-text HTTP connection that connects via a SOCKS proxy.
62     """
63     def __init__(self, *args, **kwargs):
64         self._socks_options = kwargs.pop('_socks_options')
65         super(SOCKSConnection, self).__init__(*args, **kwargs)
66 
67     def _new_conn(self):
68         """
69         Establish a new connection via the SOCKS proxy.
70         """
71         extra_kw = {}
72         if self.source_address:
73             extra_kw['source_address'] = self.source_address
74 
75         if self.socket_options:
76             extra_kw['socket_options'] = self.socket_options
77 
78         try:
79             conn = socks.create_connection(
80                 (self.host, self.port),
81                 proxy_type=self._socks_options['socks_version'],
82                 proxy_addr=self._socks_options['proxy_host'],
83                 proxy_port=self._socks_options['proxy_port'],
84                 proxy_username=self._socks_options['username'],
85                 proxy_password=self._socks_options['password'],
86                 timeout=self.timeout,
87                 **extra_kw
88             )
89 
90         except SocketTimeout as e:
91             raise ConnectTimeoutError(
92                 self, "Connection to %s timed out. (connect timeout=%s)" %
93                 (self.host, self.timeout))
94 
95         except socks.ProxyError as e:
96             # This is fragile as hell, but it seems to be the only way to raise
97             # useful errors here.
98             if e.socket_err:
99                 error = e.socket_err
100                 if isinstance(error, SocketTimeout):
101                     raise ConnectTimeoutError(
102                         self,
103                         "Connection to %s timed out. (connect timeout=%s)" %
104                         (self.host, self.timeout)
105                     )
106                 else:
107                     raise NewConnectionError(
108                         self,
109                         "Failed to establish a new connection: %s" % error
110                     )
111             else:
112                 raise NewConnectionError(
113                     self,
114                     "Failed to establish a new connection: %s" % e
115                 )
116 
117         except SocketError as e:  # Defensive: PySocks should catch all these.
118             raise NewConnectionError(
119                 self, "Failed to establish a new connection: %s" % e)
120 
121         return conn
122 
123 
124 # We don't need to duplicate the Verified/Unverified distinction from
125 # urllib3/connection.py here because the HTTPSConnection will already have been
126 # correctly set to either the Verified or Unverified form by that module. This
127 # means the SOCKSHTTPSConnection will automatically be the correct type.
128 class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):
129     pass
130 
131 
132 class SOCKSHTTPConnectionPool(HTTPConnectionPool):
133     ConnectionCls = SOCKSConnection
134 
135 
136 class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):
137     ConnectionCls = SOCKSHTTPSConnection
138 
139 
140 class SOCKSProxyManager(PoolManager):
141     """
142     A version of the urllib3 ProxyManager that routes connections via the
143     defined SOCKS proxy.
144     """
145     pool_classes_by_scheme = {
146         'http': SOCKSHTTPConnectionPool,
147         'https': SOCKSHTTPSConnectionPool,
148     }
149 
150     def __init__(self, proxy_url, username=None, password=None,
151                  num_pools=10, headers=None, **connection_pool_kw):
152         parsed = parse_url(proxy_url)
153 
154         if parsed.scheme == 'socks5':
155             socks_version = socks.PROXY_TYPE_SOCKS5
156         elif parsed.scheme == 'socks4':
157             socks_version = socks.PROXY_TYPE_SOCKS4
158         else:
159             raise ValueError(
160                 "Unable to determine SOCKS version from %s" % proxy_url
161             )
162 
163         self.proxy_url = proxy_url
164 
165         socks_options = {
166             'socks_version': socks_version,
167             'proxy_host': parsed.host,
168             'proxy_port': parsed.port,
169             'username': username,
170             'password': password,
171         }
172         connection_pool_kw['_socks_options'] = socks_options
173 
174         super(SOCKSProxyManager, self).__init__(
175             num_pools, headers, **connection_pool_kw
176         )
177 
178         self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
179
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/dummyserver/testcase.py b/dummyserver/testcase.py
--- a/dummyserver/testcase.py
+++ b/dummyserver/testcase.py
@@ -1,4 +1,4 @@
-import unittest
+import sys
 import socket
 import threading
 from nose.plugins.skip import SkipTest
@@ -13,6 +13,11 @@
 from dummyserver.handlers import TestingApp
 from dummyserver.proxy import ProxyHandler
 
+if sys.version_info >= (2, 7):
+    import unittest
+else:
+    import unittest2 as unittest
+
 
 def consume_socket(sock, chunks=65536):
     while not sock.recv(chunks).endswith(b'\r\n\r\n'):
diff --git a/urllib3/contrib/socks.py b/urllib3/contrib/socks.py
--- a/urllib3/contrib/socks.py
+++ b/urllib3/contrib/socks.py
@@ -83,6 +83,7 @@
                 proxy_port=self._socks_options['proxy_port'],
                 proxy_username=self._socks_options['username'],
                 proxy_password=self._socks_options['password'],
+                proxy_rdns=self._socks_options['rdns'],
                 timeout=self.timeout,
                 **extra_kw
             )
@@ -153,8 +154,16 @@
 
         if parsed.scheme == 'socks5':
             socks_version = socks.PROXY_TYPE_SOCKS5
+            rdns = False
+        elif parsed.scheme == 'socks5h':
+            socks_version = socks.PROXY_TYPE_SOCKS5
+            rdns = True
         elif parsed.scheme == 'socks4':
             socks_version = socks.PROXY_TYPE_SOCKS4
+            rdns = False
+        elif parsed.scheme == 'socks4a':
+            socks_version = socks.PROXY_TYPE_SOCKS4
+            rdns = True
         else:
             raise ValueError(
                 "Unable to determine SOCKS version from %s" % proxy_url
@@ -168,6 +177,7 @@
             'proxy_port': parsed.port,
             'username': username,
             'password': password,
+            'rdns': rdns
         }
         connection_pool_kw['_socks_options'] = socks_options

{"golden_diff": "diff --git a/dummyserver/testcase.py b/dummyserver/testcase.py\n--- a/dummyserver/testcase.py\n+++ b/dummyserver/testcase.py\n@@ -1,4 +1,4 @@\n-import unittest\n+import sys\n import socket\n import threading\n from nose.plugins.skip import SkipTest\n@@ -13,6 +13,11 @@\n from dummyserver.handlers import TestingApp\n from dummyserver.proxy import ProxyHandler\n \n+if sys.version_info >= (2, 7):\n+    import unittest\n+else:\n+    import unittest2 as unittest\n+\n \n def consume_socket(sock, chunks=65536):\n     while not sock.recv(chunks).endswith(b'\\r\\n\\r\\n'):\ndiff --git a/urllib3/contrib/socks.py b/urllib3/contrib/socks.py\n--- a/urllib3/contrib/socks.py\n+++ b/urllib3/contrib/socks.py\n@@ -83,6 +83,7 @@\n                 proxy_port=self._socks_options['proxy_port'],\n                 proxy_username=self._socks_options['username'],\n                 proxy_password=self._socks_options['password'],\n+                proxy_rdns=self._socks_options['rdns'],\n                 timeout=self.timeout,\n                 **extra_kw\n             )\n@@ -153,8 +154,16 @@\n \n         if parsed.scheme == 'socks5':\n             socks_version = socks.PROXY_TYPE_SOCKS5\n+            rdns = False\n+        elif parsed.scheme == 'socks5h':\n+            socks_version = socks.PROXY_TYPE_SOCKS5\n+            rdns = True\n         elif parsed.scheme == 'socks4':\n             socks_version = socks.PROXY_TYPE_SOCKS4\n+            rdns = False\n+        elif parsed.scheme == 'socks4a':\n+            socks_version = socks.PROXY_TYPE_SOCKS4\n+            rdns = True\n         else:\n             raise ValueError(\n                 \"Unable to determine SOCKS version from %s\" % proxy_url\n@@ -168,6 +177,7 @@\n             'proxy_port': parsed.port,\n             'username': username,\n             'password': password,\n+            'rdns': rdns\n         }\n         connection_pool_kw['_socks_options'] = socks_options\n", "issue": "Differentiate socks5h from socks5 and socks4a from socks4 when handling proxy string\nIn a proxy string, socks5h:// and socks4a:// mean that the hostname is\r\nresolved by the SOCKS server.  socks5:// and socks4:// mean that the\r\nhostname is resolved locally.  socks4a:// means to use SOCKS4a, which is\r\nan extension of SOCKS4.  Let's make urllib3 honor it.\n", "before_files": [{"content": "import unittest\nimport socket\nimport threading\nfrom nose.plugins.skip import SkipTest\nfrom tornado import ioloop, web\n\nfrom dummyserver.server import (\n    SocketServerThread,\n    run_tornado_app,\n    run_loop_in_thread,\n    DEFAULT_CERTS,\n)\nfrom dummyserver.handlers import TestingApp\nfrom dummyserver.proxy import ProxyHandler\n\n\ndef consume_socket(sock, chunks=65536):\n    while not sock.recv(chunks).endswith(b'\\r\\n\\r\\n'):\n        pass\n\n\nclass SocketDummyServerTestCase(unittest.TestCase):\n    \"\"\"\n    A simple socket-based server is created for this class that is good for\n    exactly one request.\n    \"\"\"\n    scheme = 'http'\n    host = 'localhost'\n\n    @classmethod\n    def _start_server(cls, socket_handler):\n        ready_event = threading.Event()\n        cls.server_thread = SocketServerThread(socket_handler=socket_handler,\n                                               ready_event=ready_event,\n                                               host=cls.host)\n        cls.server_thread.start()\n        ready_event.wait(5)\n        if not ready_event.is_set():\n            raise Exception(\"most likely failed to start server\")\n        cls.port = cls.server_thread.port\n\n    @classmethod\n    def start_response_handler(cls, response, num=1, block_send=None):\n        ready_event = threading.Event()\n\n        def socket_handler(listener):\n            for _ in range(num):\n                ready_event.set()\n\n                sock = listener.accept()[0]\n                consume_socket(sock)\n                if block_send:\n                    block_send.wait()\n                    block_send.clear()\n                sock.send(response)\n                sock.close()\n\n        cls._start_server(socket_handler)\n        return ready_event\n\n    @classmethod\n    def start_basic_handler(cls, **kw):\n        return cls.start_response_handler(\n            b'HTTP/1.1 200 OK\\r\\n'\n            b'Content-Length: 0\\r\\n'\n            b'\\r\\n', **kw)\n\n    @classmethod\n    def tearDownClass(cls):\n        if hasattr(cls, 'server_thread'):\n            cls.server_thread.join(0.1)\n\n\nclass IPV4SocketDummyServerTestCase(SocketDummyServerTestCase):\n    @classmethod\n    def _start_server(cls, socket_handler):\n        ready_event = threading.Event()\n        cls.server_thread = SocketServerThread(socket_handler=socket_handler,\n                                               ready_event=ready_event,\n                                               host=cls.host)\n        cls.server_thread.USE_IPV6 = False\n        cls.server_thread.start()\n        ready_event.wait(5)\n        if not ready_event.is_set():\n            raise Exception(\"most likely failed to start server\")\n        cls.port = cls.server_thread.port\n\n\nclass HTTPDummyServerTestCase(unittest.TestCase):\n    \"\"\" A simple HTTP server that runs when your test class runs\n\n    Have your unittest class inherit from this one, and then a simple server\n    will start when your tests run, and automatically shut down when they\n    complete. For examples of what test requests you can send to the server,\n    see the TestingApp in dummyserver/handlers.py.\n    \"\"\"\n    scheme = 'http'\n    host = 'localhost'\n    host_alt = '127.0.0.1'  # Some tests need two hosts\n    certs = DEFAULT_CERTS\n\n    @classmethod\n    def _start_server(cls):\n        cls.io_loop = ioloop.IOLoop()\n        app = web.Application([(r\".*\", TestingApp)])\n        cls.server, cls.port = run_tornado_app(app, cls.io_loop, cls.certs,\n                                               cls.scheme, cls.host)\n        cls.server_thread = run_loop_in_thread(cls.io_loop)\n\n    @classmethod\n    def _stop_server(cls):\n        cls.io_loop.add_callback(cls.server.stop)\n        cls.io_loop.add_callback(cls.io_loop.stop)\n        cls.server_thread.join()\n\n    @classmethod\n    def setUpClass(cls):\n        cls._start_server()\n\n    @classmethod\n    def tearDownClass(cls):\n        cls._stop_server()\n\n\nclass HTTPSDummyServerTestCase(HTTPDummyServerTestCase):\n    scheme = 'https'\n    host = 'localhost'\n    certs = DEFAULT_CERTS\n\n\nclass IPV6HTTPSDummyServerTestCase(HTTPSDummyServerTestCase):\n    host = '::1'\n\n    @classmethod\n    def setUpClass(cls):\n        if not socket.has_ipv6:\n            raise SkipTest('IPv6 not available')\n        else:\n            super(IPV6HTTPSDummyServerTestCase, cls).setUpClass()\n\n\nclass HTTPDummyProxyTestCase(unittest.TestCase):\n\n    http_host = 'localhost'\n    http_host_alt = '127.0.0.1'\n\n    https_host = 'localhost'\n    https_host_alt = '127.0.0.1'\n    https_certs = DEFAULT_CERTS\n\n    proxy_host = 'localhost'\n    proxy_host_alt = '127.0.0.1'\n\n    @classmethod\n    def setUpClass(cls):\n        cls.io_loop = ioloop.IOLoop()\n\n        app = web.Application([(r'.*', TestingApp)])\n        cls.http_server, cls.http_port = run_tornado_app(\n            app, cls.io_loop, None, 'http', cls.http_host)\n\n        app = web.Application([(r'.*', TestingApp)])\n        cls.https_server, cls.https_port = run_tornado_app(\n            app, cls.io_loop, cls.https_certs, 'https', cls.http_host)\n\n        app = web.Application([(r'.*', ProxyHandler)])\n        cls.proxy_server, cls.proxy_port = run_tornado_app(\n            app, cls.io_loop, None, 'http', cls.proxy_host)\n\n        cls.server_thread = run_loop_in_thread(cls.io_loop)\n\n    @classmethod\n    def tearDownClass(cls):\n        cls.io_loop.add_callback(cls.http_server.stop)\n        cls.io_loop.add_callback(cls.https_server.stop)\n        cls.io_loop.add_callback(cls.proxy_server.stop)\n        cls.io_loop.add_callback(cls.io_loop.stop)\n        cls.server_thread.join()\n\n\nclass IPv6HTTPDummyServerTestCase(HTTPDummyServerTestCase):\n    host = '::1'\n\n    @classmethod\n    def setUpClass(cls):\n        if not socket.has_ipv6:\n            raise SkipTest('IPv6 not available')\n        else:\n            super(IPv6HTTPDummyServerTestCase, cls).setUpClass()\n\n\nclass IPv6HTTPDummyProxyTestCase(HTTPDummyProxyTestCase):\n\n    http_host = 'localhost'\n    http_host_alt = '127.0.0.1'\n\n    https_host = 'localhost'\n    https_host_alt = '127.0.0.1'\n    https_certs = DEFAULT_CERTS\n\n    proxy_host = '::1'\n    proxy_host_alt = '127.0.0.1'\n", "path": "dummyserver/testcase.py"}, {"content": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and\nSOCKS5. To enable its functionality, either install PySocks or install this\nmodule with the ``socks`` extra.\n\nThe SOCKS implementation supports the full range of urllib3 features. It also\nsupports the following SOCKS features:\n\n- SOCKS4\n- SOCKS4a\n- SOCKS5\n- Usernames and passwords for the SOCKS proxy\n\nKnown Limitations:\n\n- Currently PySocks does not support contacting remote websites via literal\n  IPv6 addresses. Any such connection attempt will fail. You must use a domain\n  name.\n- Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any\n  such connection attempt will fail.\n\"\"\"\nfrom __future__ import absolute_import\n\ntry:\n    import socks\nexcept ImportError:\n    import warnings\n    from ..exceptions import DependencyWarning\n\n    warnings.warn((\n        'SOCKS support in urllib3 requires the installation of optional '\n        'dependencies: specifically, PySocks.  For more information, see '\n        'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies'\n        ),\n        DependencyWarning\n    )\n    raise\n\nfrom socket import error as SocketError, timeout as SocketTimeout\n\nfrom ..connection import (\n    HTTPConnection, HTTPSConnection\n)\nfrom ..connectionpool import (\n    HTTPConnectionPool, HTTPSConnectionPool\n)\nfrom ..exceptions import ConnectTimeoutError, NewConnectionError\nfrom ..poolmanager import PoolManager\nfrom ..util.url import parse_url\n\ntry:\n    import ssl\nexcept ImportError:\n    ssl = None\n\n\nclass SOCKSConnection(HTTPConnection):\n    \"\"\"\n    A plain-text HTTP connection that connects via a SOCKS proxy.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        self._socks_options = kwargs.pop('_socks_options')\n        super(SOCKSConnection, self).__init__(*args, **kwargs)\n\n    def _new_conn(self):\n        \"\"\"\n        Establish a new connection via the SOCKS proxy.\n        \"\"\"\n        extra_kw = {}\n        if self.source_address:\n            extra_kw['source_address'] = self.source_address\n\n        if self.socket_options:\n            extra_kw['socket_options'] = self.socket_options\n\n        try:\n            conn = socks.create_connection(\n                (self.host, self.port),\n                proxy_type=self._socks_options['socks_version'],\n                proxy_addr=self._socks_options['proxy_host'],\n                proxy_port=self._socks_options['proxy_port'],\n                proxy_username=self._socks_options['username'],\n                proxy_password=self._socks_options['password'],\n                timeout=self.timeout,\n                **extra_kw\n            )\n\n        except SocketTimeout as e:\n            raise ConnectTimeoutError(\n                self, \"Connection to %s timed out. (connect timeout=%s)\" %\n                (self.host, self.timeout))\n\n        except socks.ProxyError as e:\n            # This is fragile as hell, but it seems to be the only way to raise\n            # useful errors here.\n            if e.socket_err:\n                error = e.socket_err\n                if isinstance(error, SocketTimeout):\n                    raise ConnectTimeoutError(\n                        self,\n                        \"Connection to %s timed out. (connect timeout=%s)\" %\n                        (self.host, self.timeout)\n                    )\n                else:\n                    raise NewConnectionError(\n                        self,\n                        \"Failed to establish a new connection: %s\" % error\n                    )\n            else:\n                raise NewConnectionError(\n                    self,\n                    \"Failed to establish a new connection: %s\" % e\n                )\n\n        except SocketError as e:  # Defensive: PySocks should catch all these.\n            raise NewConnectionError(\n                self, \"Failed to establish a new connection: %s\" % e)\n\n        return conn\n\n\n# We don't need to duplicate the Verified/Unverified distinction from\n# urllib3/connection.py here because the HTTPSConnection will already have been\n# correctly set to either the Verified or Unverified form by that module. This\n# means the SOCKSHTTPSConnection will automatically be the correct type.\nclass SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):\n    pass\n\n\nclass SOCKSHTTPConnectionPool(HTTPConnectionPool):\n    ConnectionCls = SOCKSConnection\n\n\nclass SOCKSHTTPSConnectionPool(HTTPSConnectionPool):\n    ConnectionCls = SOCKSHTTPSConnection\n\n\nclass SOCKSProxyManager(PoolManager):\n    \"\"\"\n    A version of the urllib3 ProxyManager that routes connections via the\n    defined SOCKS proxy.\n    \"\"\"\n    pool_classes_by_scheme = {\n        'http': SOCKSHTTPConnectionPool,\n        'https': SOCKSHTTPSConnectionPool,\n    }\n\n    def __init__(self, proxy_url, username=None, password=None,\n                 num_pools=10, headers=None, **connection_pool_kw):\n        parsed = parse_url(proxy_url)\n\n        if parsed.scheme == 'socks5':\n            socks_version = socks.PROXY_TYPE_SOCKS5\n        elif parsed.scheme == 'socks4':\n            socks_version = socks.PROXY_TYPE_SOCKS4\n        else:\n            raise ValueError(\n                \"Unable to determine SOCKS version from %s\" % proxy_url\n            )\n\n        self.proxy_url = proxy_url\n\n        socks_options = {\n            'socks_version': socks_version,\n            'proxy_host': parsed.host,\n            'proxy_port': parsed.port,\n            'username': username,\n            'password': password,\n        }\n        connection_pool_kw['_socks_options'] = socks_options\n\n        super(SOCKSProxyManager, self).__init__(\n            num_pools, headers, **connection_pool_kw\n        )\n\n        self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme\n", "path": "urllib3/contrib/socks.py"}], "after_files": [{"content": "import sys\nimport socket\nimport threading\nfrom nose.plugins.skip import SkipTest\nfrom tornado import ioloop, web\n\nfrom dummyserver.server import (\n    SocketServerThread,\n    run_tornado_app,\n    run_loop_in_thread,\n    DEFAULT_CERTS,\n)\nfrom dummyserver.handlers import TestingApp\nfrom dummyserver.proxy import ProxyHandler\n\nif sys.version_info >= (2, 7):\n    import unittest\nelse:\n    import unittest2 as unittest\n\n\ndef consume_socket(sock, chunks=65536):\n    while not sock.recv(chunks).endswith(b'\\r\\n\\r\\n'):\n        pass\n\n\nclass SocketDummyServerTestCase(unittest.TestCase):\n    \"\"\"\n    A simple socket-based server is created for this class that is good for\n    exactly one request.\n    \"\"\"\n    scheme = 'http'\n    host = 'localhost'\n\n    @classmethod\n    def _start_server(cls, socket_handler):\n        ready_event = threading.Event()\n        cls.server_thread = SocketServerThread(socket_handler=socket_handler,\n                                               ready_event=ready_event,\n                                               host=cls.host)\n        cls.server_thread.start()\n        ready_event.wait(5)\n        if not ready_event.is_set():\n            raise Exception(\"most likely failed to start server\")\n        cls.port = cls.server_thread.port\n\n    @classmethod\n    def start_response_handler(cls, response, num=1, block_send=None):\n        ready_event = threading.Event()\n\n        def socket_handler(listener):\n            for _ in range(num):\n                ready_event.set()\n\n                sock = listener.accept()[0]\n                consume_socket(sock)\n                if block_send:\n                    block_send.wait()\n                    block_send.clear()\n                sock.send(response)\n                sock.close()\n\n        cls._start_server(socket_handler)\n        return ready_event\n\n    @classmethod\n    def start_basic_handler(cls, **kw):\n        return cls.start_response_handler(\n            b'HTTP/1.1 200 OK\\r\\n'\n            b'Content-Length: 0\\r\\n'\n            b'\\r\\n', **kw)\n\n    @classmethod\n    def tearDownClass(cls):\n        if hasattr(cls, 'server_thread'):\n            cls.server_thread.join(0.1)\n\n\nclass IPV4SocketDummyServerTestCase(SocketDummyServerTestCase):\n    @classmethod\n    def _start_server(cls, socket_handler):\n        ready_event = threading.Event()\n        cls.server_thread = SocketServerThread(socket_handler=socket_handler,\n                                               ready_event=ready_event,\n                                               host=cls.host)\n        cls.server_thread.USE_IPV6 = False\n        cls.server_thread.start()\n        ready_event.wait(5)\n        if not ready_event.is_set():\n            raise Exception(\"most likely failed to start server\")\n        cls.port = cls.server_thread.port\n\n\nclass HTTPDummyServerTestCase(unittest.TestCase):\n    \"\"\" A simple HTTP server that runs when your test class runs\n\n    Have your unittest class inherit from this one, and then a simple server\n    will start when your tests run, and automatically shut down when they\n    complete. For examples of what test requests you can send to the server,\n    see the TestingApp in dummyserver/handlers.py.\n    \"\"\"\n    scheme = 'http'\n    host = 'localhost'\n    host_alt = '127.0.0.1'  # Some tests need two hosts\n    certs = DEFAULT_CERTS\n\n    @classmethod\n    def _start_server(cls):\n        cls.io_loop = ioloop.IOLoop()\n        app = web.Application([(r\".*\", TestingApp)])\n        cls.server, cls.port = run_tornado_app(app, cls.io_loop, cls.certs,\n                                               cls.scheme, cls.host)\n        cls.server_thread = run_loop_in_thread(cls.io_loop)\n\n    @classmethod\n    def _stop_server(cls):\n        cls.io_loop.add_callback(cls.server.stop)\n        cls.io_loop.add_callback(cls.io_loop.stop)\n        cls.server_thread.join()\n\n    @classmethod\n    def setUpClass(cls):\n        cls._start_server()\n\n    @classmethod\n    def tearDownClass(cls):\n        cls._stop_server()\n\n\nclass HTTPSDummyServerTestCase(HTTPDummyServerTestCase):\n    scheme = 'https'\n    host = 'localhost'\n    certs = DEFAULT_CERTS\n\n\nclass IPV6HTTPSDummyServerTestCase(HTTPSDummyServerTestCase):\n    host = '::1'\n\n    @classmethod\n    def setUpClass(cls):\n        if not socket.has_ipv6:\n            raise SkipTest('IPv6 not available')\n        else:\n            super(IPV6HTTPSDummyServerTestCase, cls).setUpClass()\n\n\nclass HTTPDummyProxyTestCase(unittest.TestCase):\n\n    http_host = 'localhost'\n    http_host_alt = '127.0.0.1'\n\n    https_host = 'localhost'\n    https_host_alt = '127.0.0.1'\n    https_certs = DEFAULT_CERTS\n\n    proxy_host = 'localhost'\n    proxy_host_alt = '127.0.0.1'\n\n    @classmethod\n    def setUpClass(cls):\n        cls.io_loop = ioloop.IOLoop()\n\n        app = web.Application([(r'.*', TestingApp)])\n        cls.http_server, cls.http_port = run_tornado_app(\n            app, cls.io_loop, None, 'http', cls.http_host)\n\n        app = web.Application([(r'.*', TestingApp)])\n        cls.https_server, cls.https_port = run_tornado_app(\n            app, cls.io_loop, cls.https_certs, 'https', cls.http_host)\n\n        app = web.Application([(r'.*', ProxyHandler)])\n        cls.proxy_server, cls.proxy_port = run_tornado_app(\n            app, cls.io_loop, None, 'http', cls.proxy_host)\n\n        cls.server_thread = run_loop_in_thread(cls.io_loop)\n\n    @classmethod\n    def tearDownClass(cls):\n        cls.io_loop.add_callback(cls.http_server.stop)\n        cls.io_loop.add_callback(cls.https_server.stop)\n        cls.io_loop.add_callback(cls.proxy_server.stop)\n        cls.io_loop.add_callback(cls.io_loop.stop)\n        cls.server_thread.join()\n\n\nclass IPv6HTTPDummyServerTestCase(HTTPDummyServerTestCase):\n    host = '::1'\n\n    @classmethod\n    def setUpClass(cls):\n        if not socket.has_ipv6:\n            raise SkipTest('IPv6 not available')\n        else:\n            super(IPv6HTTPDummyServerTestCase, cls).setUpClass()\n\n\nclass IPv6HTTPDummyProxyTestCase(HTTPDummyProxyTestCase):\n\n    http_host = 'localhost'\n    http_host_alt = '127.0.0.1'\n\n    https_host = 'localhost'\n    https_host_alt = '127.0.0.1'\n    https_certs = DEFAULT_CERTS\n\n    proxy_host = '::1'\n    proxy_host_alt = '127.0.0.1'\n", "path": "dummyserver/testcase.py"}, {"content": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and\nSOCKS5. To enable its functionality, either install PySocks or install this\nmodule with the ``socks`` extra.\n\nThe SOCKS implementation supports the full range of urllib3 features. It also\nsupports the following SOCKS features:\n\n- SOCKS4\n- SOCKS4a\n- SOCKS5\n- Usernames and passwords for the SOCKS proxy\n\nKnown Limitations:\n\n- Currently PySocks does not support contacting remote websites via literal\n  IPv6 addresses. Any such connection attempt will fail. You must use a domain\n  name.\n- Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any\n  such connection attempt will fail.\n\"\"\"\nfrom __future__ import absolute_import\n\ntry:\n    import socks\nexcept ImportError:\n    import warnings\n    from ..exceptions import DependencyWarning\n\n    warnings.warn((\n        'SOCKS support in urllib3 requires the installation of optional '\n        'dependencies: specifically, PySocks.  For more information, see '\n        'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies'\n        ),\n        DependencyWarning\n    )\n    raise\n\nfrom socket import error as SocketError, timeout as SocketTimeout\n\nfrom ..connection import (\n    HTTPConnection, HTTPSConnection\n)\nfrom ..connectionpool import (\n    HTTPConnectionPool, HTTPSConnectionPool\n)\nfrom ..exceptions import ConnectTimeoutError, NewConnectionError\nfrom ..poolmanager import PoolManager\nfrom ..util.url import parse_url\n\ntry:\n    import ssl\nexcept ImportError:\n    ssl = None\n\n\nclass SOCKSConnection(HTTPConnection):\n    \"\"\"\n    A plain-text HTTP connection that connects via a SOCKS proxy.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        self._socks_options = kwargs.pop('_socks_options')\n        super(SOCKSConnection, self).__init__(*args, **kwargs)\n\n    def _new_conn(self):\n        \"\"\"\n        Establish a new connection via the SOCKS proxy.\n        \"\"\"\n        extra_kw = {}\n        if self.source_address:\n            extra_kw['source_address'] = self.source_address\n\n        if self.socket_options:\n            extra_kw['socket_options'] = self.socket_options\n\n        try:\n            conn = socks.create_connection(\n                (self.host, self.port),\n                proxy_type=self._socks_options['socks_version'],\n                proxy_addr=self._socks_options['proxy_host'],\n                proxy_port=self._socks_options['proxy_port'],\n                proxy_username=self._socks_options['username'],\n                proxy_password=self._socks_options['password'],\n                proxy_rdns=self._socks_options['rdns'],\n                timeout=self.timeout,\n                **extra_kw\n            )\n\n        except SocketTimeout as e:\n            raise ConnectTimeoutError(\n                self, \"Connection to %s timed out. (connect timeout=%s)\" %\n                (self.host, self.timeout))\n\n        except socks.ProxyError as e:\n            # This is fragile as hell, but it seems to be the only way to raise\n            # useful errors here.\n            if e.socket_err:\n                error = e.socket_err\n                if isinstance(error, SocketTimeout):\n                    raise ConnectTimeoutError(\n                        self,\n                        \"Connection to %s timed out. (connect timeout=%s)\" %\n                        (self.host, self.timeout)\n                    )\n                else:\n                    raise NewConnectionError(\n                        self,\n                        \"Failed to establish a new connection: %s\" % error\n                    )\n            else:\n                raise NewConnectionError(\n                    self,\n                    \"Failed to establish a new connection: %s\" % e\n                )\n\n        except SocketError as e:  # Defensive: PySocks should catch all these.\n            raise NewConnectionError(\n                self, \"Failed to establish a new connection: %s\" % e)\n\n        return conn\n\n\n# We don't need to duplicate the Verified/Unverified distinction from\n# urllib3/connection.py here because the HTTPSConnection will already have been\n# correctly set to either the Verified or Unverified form by that module. This\n# means the SOCKSHTTPSConnection will automatically be the correct type.\nclass SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):\n    pass\n\n\nclass SOCKSHTTPConnectionPool(HTTPConnectionPool):\n    ConnectionCls = SOCKSConnection\n\n\nclass SOCKSHTTPSConnectionPool(HTTPSConnectionPool):\n    ConnectionCls = SOCKSHTTPSConnection\n\n\nclass SOCKSProxyManager(PoolManager):\n    \"\"\"\n    A version of the urllib3 ProxyManager that routes connections via the\n    defined SOCKS proxy.\n    \"\"\"\n    pool_classes_by_scheme = {\n        'http': SOCKSHTTPConnectionPool,\n        'https': SOCKSHTTPSConnectionPool,\n    }\n\n    def __init__(self, proxy_url, username=None, password=None,\n                 num_pools=10, headers=None, **connection_pool_kw):\n        parsed = parse_url(proxy_url)\n\n        if parsed.scheme == 'socks5':\n            socks_version = socks.PROXY_TYPE_SOCKS5\n            rdns = False\n        elif parsed.scheme == 'socks5h':\n            socks_version = socks.PROXY_TYPE_SOCKS5\n            rdns = True\n        elif parsed.scheme == 'socks4':\n            socks_version = socks.PROXY_TYPE_SOCKS4\n            rdns = False\n        elif parsed.scheme == 'socks4a':\n            socks_version = socks.PROXY_TYPE_SOCKS4\n            rdns = True\n        else:\n            raise ValueError(\n                \"Unable to determine SOCKS version from %s\" % proxy_url\n            )\n\n        self.proxy_url = proxy_url\n\n        socks_options = {\n            'socks_version': socks_version,\n            'proxy_host': parsed.host,\n            'proxy_port': parsed.port,\n            'username': username,\n            'password': password,\n            'rdns': rdns\n        }\n        connection_pool_kw['_socks_options'] = socks_options\n\n        super(SOCKSProxyManager, self).__init__(\n            num_pools, headers, **connection_pool_kw\n        )\n\n        self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme\n", "path": "urllib3/contrib/socks.py"}]}